Блог пользователя amnchouhn

Автор amnchouhn, история, 5 часов назад, По-английски

I have found a very short solution of 1997C - Even Positions compared to what's available everywhere. Please upvote if found helpful.

Shayan, adedalic, BledDest, Neon, awoo Is there any edge case for this solution?

#include <bits/stdc++.h>
using namespace std;
#define nl '\n'
#define FAST_IO ios::sync_with_stdio(false); cin.tie(nullptr);

void solve() {
	int n; cin >> n;
	string s; cin >> s;
	int ans = 0;
	for (int i = 0; i < n; i += 2) {
		if (s[i + 1] == ')') {
			ans += 1;
		}
		else {
			ans += 3;
		}
	}
	cout << ans << nl;
}

int main() {
	FAST_IO
	int tc; cin >> tc;
	while (tc--) {solve();}
}
  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
5 часов назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by amnchouhn (previous revision, new revision, compare).

»
5 часов назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by amnchouhn (previous revision, new revision, compare).

»
3 часа назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

This is pretty clever! Starting from the end of the string helped me understand this approach -- the last character must be a ')', and from there you can have either -)-) or -(-). In the first case, you can do -)(), and ignore the last block () of size 2, adding 1 to the answer. Otherwise, for -(-) the next best thing to do is (()), adding 3 to the answer and ignoring the this last block of size 4. I think this solution works great!

»
104 минуты назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

shorter one

i still don't get how it works lol

  • »
    »
    82 минуты назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Realized a flaw in my previous reasoning that aligns with the solution you mentioned -- starting from the back, we can only block off when you hit another ')'. Until then, we have something like )-(-(...-(-). Now, a ')' can be greedily put in every space except the first one from the left. That needs to be a '(' to block it off. So we can think of each '(' as adding 3 to the answer: 1 for the '()' that's formed, and 2 for the cost of the last ')', which is paired with the first '(' in the block. The fixed ')' at the end also adds 1 to its cost.

    The solution you mentioned works similarly -- it adds 1 for each '()' at the start with pairs/2. Then it counts the extra +2s for each '('. Hope that helps =D