We need to count positions i (1-indexed) such that flipping the bracket at that position makes the whole string become a regular bracket sequence. Let's denote original string s of length n, containing '(' and ')'.
We need to find i such that after flipping s[i] (i.e., '(' -> ')' or ')' -> '('), the resulting string is a regular bracket sequence.
Observations: For a string to be regular bracket sequence (RBS) of length n, n must be even. But we are only flipping one character; after flipping, the length remains n. So if n is odd, it's impossible to have a regular bracket sequence. However, the problem does not guarantee even n. But if n is odd, then flipping any position cannot make it regular, because any regular bracket sequence must have even length. So answer = 0 if n is odd. (Check: Example 3: n=1, string = ')', output 0. So matches.)
Assume n is even. We need to count i such that after flipping, the string is a regular bracket sequence.
We need to check for each i quickly. n up to 1e6, so O(n) or O(n log n) is fine.
Let's denote original string s. For a string to be RBS, it must satisfy:
- The total number of '(' equals total number of ')', i.e., exactly n/2 each.
- For any prefix, number of '(' >= number of ')'.
Alternatively, it's characterized by: total balance = 0 and min balance >= 0.
Define balance: start 0; for each char: '(' adds +1, ')' adds -1. The condition for RBS is that the final balance is 0 and all prefix balances >= 0.
When we flip a character at position i, we effectively change its contribution: originally if '(' => +1, becomes -1, so delta = -2; if ')' => -1 becomes +1, delta = +2. So total balance after flip = total_balance_original + delta_i (where delta_i = -2 if original '('; +2 if original ')') . For the string to be RBS, final total must be 0.
Thus, one necessary condition: total_balance_original + delta_i = 0 => delta_i = -total_balance_original. Since delta_i is either +2 or -2, the required delta_i must be either +2 or -2. So if total_balance_original is not among -2, 0, 2? Actually: delta_i = -total_original. If total_original is, say, B. Then we need B + delta_i = 0 => delta_i = -B. But delta_i is ±2 (unless we consider flipping something that doesn't change? But we must flip; we cannot not flip). So for a solution to exist, -B must be either +2 or -2, i.e., B must be either 2 or -2. Wait: also if B = 0, then we need delta_i = 0, but delta_i is ±2, so impossible. So if original total balance is 0, flipping one character changes total balance to ±2, not 0. So cannot become regular. Therefore, the only possible case where flipping one bracket yields total balance 0 is when original total balance is ±2. Because then we can flip a bracket that changes total balance by ∓2 to bring to 0. That is: if B = 2, we need to flip a '(' (delta=-2) to get 0. If B = -2, we need to flip a ')' (delta=+2) to get 0. If |B| != 2, answer = 0. Also if n odd, answer = 0 (but this already gives B odd? Actually if n odd, B is odd because total # '(' minus # ')' = (# '(' - # ')') and n odd => total # '(' + # ')' odd, so difference odd, but could be ±1, ±3, etc. Not ±2 necessarily. But anyway it's 0 due to length odd.)
Thus first condition: |B| = 2, and the bracket we flip must be of a particular type: if B = 2, we must flip a '(' to ')'; if B = -2, we must flip a ')' to '('.
But that's not sufficient; we also need the prefix condition (all balances >= 0). So we need to check for each candidate i (with appropriate original bracket type) whether after flipping, the resulting string has all prefix balances >= 0.
We can evaluate prefix balances of the modified string without reconstructing the whole string each time; we can precompute something.
Let original string s. Define prefix balance array pre[i] = balance after processing first i characters (1-indexed). So pre[0] = 0; for i from 1 to n: pre[i] = pre[i-1] + (s[i] == '(' ? 1 : -1).
Similarly, suffix balance? The condition all prefix balances >=0 and final balance 0. After flipping at position i, the balances for positions before i remain unchanged, because they are not affected. For positions after i, the balances are shifted by the effect of the flip: Since flipping changes the contribution at i by delta (delta = -2 if original '(' -> ')', else +2), then for all positions j >= i, the cumulative balance becomes original pre[j] + delta (since we added delta at i). But careful: The balance after processing up to j is pre[j] originally. After flipping at i, the contribution of character i changes by delta, so the new balance at position j (j >= i) is pre[j] + delta. However, we also need to check intermediate steps between i and j: because the balance after each step is simply original pre[k] + delta for k >= i (since delta is added at i and persists). Yes, because the delta is applied at i and not reversed.
Thus the new prefix balances are:
- For j < i: new_pre[j] = pre[j] (unchanged).
- For j >= i: new_pre[j] = pre[j] + delta.
We need:
- For all j from 1 to n: new_pre[j] >= 0.
- Also new_pre[n] = pre[n] + delta = 0 (we already ensured delta = -pre[n] because pre[n] = B, and we have delta = -B to get final 0; but also we require that the type of bracket matches delta accordingly). So final balance condition automatically satisfied if we flip appropriate type.
So we need:
- For all j < i: pre[j] >= 0.
- For all j >= i: pre[j] + delta >= 0.
Since delta = -B. For B=2, delta = -2; for B=-2, delta = +2.
We also need to ensure that at the flipped position itself, new_pre[i] = pre[i] + delta >= 0? It's included.
Now, we also need to consider the effect on the entire string: The new prefix balances must be nonnegative. Also, note that if we flip a '(' to ')', delta = -2, so we subtract 2 from all balances from i onward. This could make some later prefix negative if original pre[j] is small (<2). So we need to check for all j >= i: pre[j] >= 2 (since delta = -2). For B=-2, delta = +2, we need pre[j] + 2 >= 0 => pre[j] >= -2? Actually pre[j] could be negative originally; but we need new pre[j] >= 0 => pre[j] + 2 >= 0 => pre[j] >= -2. But also note that for j < i, we require pre[j] >= 0. So the conditions:
Case A: B = 2 (more '(' than ')'). Then we need to flip a '(' to ')', delta = -2. Conditions:
- For all j < i: pre[j] >= 0.
- For all j >= i: pre[j] >= 2. (since pre[j] + (-2) >= 0 => pre[j] >= 2)
Case B: B = -2 (more ')' than '('). Then we need to flip a ')' to '(', delta = +2. Conditions:
- For all j < i: pre[j] >= 0.
- For all j >= i: pre[j] >= -2? Wait: pre[j] + 2 >= 0 => pre[j] >= -2. But also need pre[j] + 2 >= 0. That's equivalent to pre[j] >= -2. However, is it enough? Because pre[j] could be less than -2? But if original pre[j] is less than -2, after adding 2 it's still negative. So we need pre[j] >= -2. However, note that for j < i, we also have pre[j] >= 0. So the condition for j >= i is pre[j] >= -2.
But also consider: The final balance after flip is 0, so pre[n] + delta = B + delta = 0. For B = -2, delta = 2, so pre[n] = -2, pre[n] + 2 = 0, which is ok.
Now we need to count positions i such that s[i] is of required type ( '(' for B=2? Actually for B=2 we need to flip '(' -> ')', so s[i] must be '('; for B=-2 we need s[i] = ')' ) AND the prefix conditions hold.
But wait, there might be an additional subtlety: After flipping, we need the entire sequence to be a regular bracket sequence. We used the condition that final balance 0 and all prefix balances >=0. Is that sufficient? Yes, for bracket sequences with only '(' and ')', that's the definition.
Thus, we need to efficiently count i satisfying:
-
Type condition: if B=2, s[i] = '('; if B=-2, s[i] = ')'.
-
For all j < i: pre[j] >= 0. (prefix condition before i)
-
For all j >= i: pre[j] + delta >= 0. Equivalent condition: min_{j >= i} pre[j] >= -delta? Actually pre[j] + delta >= 0 => pre[j] >= -delta. For delta = -2, -delta = 2; For delta = +2, -delta = -2. So:
- If delta = -2: need min_{j >= i} pre[j] >= 2.
- If delta = +2: need min_{j >= i} pre[j] >= -2.
But also we need to check that pre[i-1] is the balance before i, and after flipping at i we also need new_pre[i] >= 0. That is included in the j>=i condition because for j=i, pre[i] + delta >=0. However, note that pre[i] depends on s[i] originally. For delta = -2, pre[i] = pre[i-1] + (original contribution). Since original contribution is +1 for '(' (since we are flipping a '('), then pre[i] = pre[i-1] + 1. So condition pre[i] >= 2 is needed. This could be derived.
Additionally, the condition for j < i: pre[j] >= 0. That essentially means that the original sequence up to i-1 must be a valid prefix (nonnegative). Since we are flipping only at i, if there was any negative prefix before i, flipping later won't fix that. So i must be such that all prefixes before i are nonnegative.
Similarly, for j >= i, the condition is on the original pre[j] values after adjusting.
We can precompute prefix minima to check quickly.
Let’s define:
- min_prefix_before[i] = minimum pre[j] for j from 0 to i-1? Actually we need for each i, we need that all pre[j] for j < i are >=0. That is equivalent to the minimum of pre[0..i-1] >= 0? Actually pre[0] = 0, which is >=0. So we need min_{0 <= j <= i-1} pre[j] >= 0. We can precompute an array that tells us the minimum prefix encountered up to each index, but we need per i.
But simpler: we can precompute an array "good_prefix[i]" that indicates whether all prefixes up to i are nonnegative. We can compute a boolean array "valid_pref_up_to[i]" = true if for all j<=i, pre[j]>=0. This can be computed by scanning and tracking current min. Actually we can compute an array "min_prefix_sofar[i]" = minimum pre[j] for j from 0 to i. Then condition min_prefix_sofar[i-1] >= 0.
Alternatively, we can compute an array "bad" positions where pre[j] < 0; then any i that is after such a position (i > j) would fail the j < i condition because that j is < i and pre[j] < 0. So i must be before the first occurrence of a negative prefix? But careful: if we have a negative prefix at some j, then for any i > j, the condition "for all j < i" would include that negative prefix, so fails. So i must be less than or equal to the first index where pre becomes negative? Actually if at index j, pre[j] < 0, then any i > j would have j < i, thus fails. So i must be ≤ the first index where pre becomes negative? But if i = j, then condition for j < i: j < i means indices strictly less than i. At i = j, does it include j? No, because j < i? Actually j is the index where pre[j] < 0. If i = j, then the set j < i includes indices 0...j-1, not j itself. So the negative prefix at j is not required to be >=0 because j is not < i (since i=j). However, we also have condition for j >= i: we need pre[j] + delta >= 0. For i = j, we need to check j itself as part of j >= i, so we require pre[j] + delta >= 0. So it's possible that i can be at the position where originally pre[j] is negative if delta is +2 (B=-2) and pre[j] >= -2. So i can be at or after the first negative prefix as long as the adjusted values become nonnegative. However, the condition for indices before i must be >=0; those before i are all indices < i. So if the first negative prefix occurs at index k, then for i > k, indices < i include k, which is negative, so fails. So i cannot be > k. i can be ≤ k? If i = k, then indices < i are 0..k-1, which might all be nonnegative (if they are). So it's okay if pre[k] itself is negative, because we will adjust it. So i must be ≤ the first index where pre becomes negative? Actually i cannot be greater than the first negative prefix index, because then that negative prefix is among indices < i and would violate pre[j] >= 0. So i must be ≤ the first index where pre becomes negative. But also if there are multiple negative prefixes, the first one already blocks all later i. So i must be ≤ the index of the first negative prefix (if any). However, what if there is a negative prefix and then later becomes positive? That doesn't matter because first negative blocks. So the condition "for all j < i: pre[j] >= 0" is equivalent to i <= firstBad, where firstBad is the smallest index j such that pre[j] < 0. If no such j exists (i.e., all pre >=0), then any i is allowed? But note pre[0]=0, so if all pre >=0, then i can be any. However, we also must ensure that for j >= i, pre[j] + delta >=0. So we need to compute for each i satisfying type condition, whether both conditions hold.
But careful: Is it strictly that i <= firstBad? Actually if firstBad = k, then for i = k+1, indices < i include k, which has pre[k] < 0 => fails. So i must be ≤ k. For i = k, indices < i are 0..k-1; that's okay if they are all >=0. So i = k is allowed, as long as other conditions hold. So indeed, condition for i: the minimum prefix value among indices [0, i-1] must be ≥0. This is equivalent to i being ≤ the first index where prefix becomes negative? Not exactly: If first negative occurs at index k, then for i = k+1, the set includes k, so fails. For i = k, the set does not include k, so passes. So i must be ≤ first negative index. That is correct. But if there is no negative prefix, then all i are allowed.
Thus we can compute first_neg = min index j (1..n) such that pre[j] < 0; if none, set first_neg = n+1 maybe? Then i must satisfy i ≤ first_neg (since indices start at 1). But note that i ranges from 1 to n. So condition: i ≤ first_neg. Actually we need to check j < i, so if first_neg = k, then for i = k, we are okay; for i = k+1, not okay. So i ≤ k. So yes, i must be ≤ first_neg. But careful: if first_neg = 1? Then pre[1] < 0. Then i must be ≤ 1, so only i=1 is allowed? Let's check: s[1] is '(' or ')', if first prefix negative at position 1, then pre[1] <0. For i=1, indices <1 are none, so condition holds. For i=2, indices <2 include index1 which is negative, fails. So i ≤ 1, correct.
Now the second condition: For all j >= i: pre[j] + delta >= 0. That is equivalent to min_{j >= i} pre[j] >= threshold, where threshold = -delta. As we defined:
- For delta = -2 (B=2): threshold = 2. So need min_{j >= i} pre[j] >= 2.
- For delta = +2 (B=-2): threshold = -2. So need min_{j >= i} pre[j] >= -2.
Note: For j >= i, we include j = i to n. So we need to compute suffix minima of pre values, but note we need the minimum of pre[j] for j from i to n inclusive. Let suf_min[i] = min_{j=i..n} pre[j]. Then condition: suf_min[i] >= threshold.
But careful: The pre values we are using are the original ones. After flipping, the balances for j >= i become pre[j] + delta. So if we check min (pre[j] + delta) >= 0, that's equivalent to min pre[j] >= -delta. So indeed suf_min[i] >= -delta.
However, we must also consider that flipping the character also changes the contribution at i, and the suffix minima might be impacted by the flip? But we already accounted by using original pre[j] with delta. But is the condition that for all j >= i, new_pre[j] >= 0 sufficient to ensure that the whole string is valid? Yes.
But we need to be careful about the fact that the flip changes the suffix balances uniformly by delta, but does it affect the relative ordering? The condition min_{j>=i} (pre[j] + delta) >= 0 is correct.
Thus the overall check:
-
If n is odd: answer = 0.
-
Compute total balance B = pre[n]. If |B| != 2: answer = 0.
-
Otherwise, let delta = -B (so delta = -2 if B=2, delta = +2 if B=-2). Let required_type = '(' if B == 2? Actually if B=2, we need to flip '(' -> ')', so original must be '('; if B=-2, flip ')' -> '(', so original must be ')'.
-
Compute prefix array pre[0..n].
-
Find first_neg: smallest index j (1<=j<=n) such that pre[j] < 0. If none, set first_neg = n+1 (or something > n). Then condition1: i <= first_neg.
-
Compute suffix minima: suf_min[i] = min_{j=i}^{n} pre[j]. Typically we compute from right: suf_min[i] = min(pre[i], suf_min[i+1]), with suf_min[n+1] = INF? Actually we need up to n. Let's compute array suffix_min[i] for i from 1 to n: suffix_min[i] = minimum of pre[j] for j in [i, n]. Also we might need suffix_min[i+1] but we can compute.
-
Condition2: suffix_min[i] >= threshold, where threshold = -delta: if delta = -2, threshold = 2; if delta = +2, threshold = -2.
But note: In case delta = +2, threshold = -2. Since pre values could be negative, we need suffix_min[i] >= -2. However, is that sufficient? Let's test examples.
We must also ensure that after flipping, the balance never goes negative at any prefix. That includes positions before i. Condition1 ensures that for j < i, pre[j] >= 0. However, note that after flipping, the balances for j < i are unchanged, so condition1 is necessary and sufficient for them.
But is there any interaction? For j >= i, we check new pre[j] = pre[j] + delta >= 0. That's sufficient. So overall, the two conditions are exactly what we need.
Now we need to count i such that:
- s[i] is of required_type ( '(' for B=2, ')' for B=-2 )
- i <= first_neg
- suffix_min[i] >= threshold.
But wait, there is nuance: The suffix_min[i] uses original pre values including pre[i] which is computed with original character s[i]. After flipping, the contribution at i changes, and the pre values after i also shift. However, the suffix_min[i] condition uses original pre values. For j >= i, the new balance is pre[j] + delta. So we need to ensure that min_{j >= i} (pre[j] + delta) >= 0, i.e., min_{j >= i} pre[j] >= -delta. That's correct. So suffix_min[i] >= -delta.
But what about i itself? For i, new pre[i] = pre[i] + delta. But pre[i] includes the original character's contribution. However, suffix_min[i] includes pre[i]. So condition ensures pre[i] >= -delta, so pre[i] + delta >= 0. Good.
Also, for j > i, same.
Thus algorithm appears sound.
But we need to double-check with some examples.
Example 1:
n=6, s="(((()))"? Actually input: "(((()))"? Let's read example: Input:
6
(((())
That string: "(((()))"? Wait they gave "(((()))"? Actually they wrote:
6
(((())
But that's 5 characters? Let's count: "(((()))"? I need to parse: the example shows:
6
((((()
But that seems 6? Let's manually: "(((()))"? Actually the example says:
Input
6
((((()
Wait, the formatting: they wrote:
6
(((())
But there is a mismatch: n=6 but string "(((()))"? Possibly it's "(((()))"? Let's search memory: I recall Codeforces problem "Bracket Subsequence" maybe? Actually the problem is "Bracket Sequence" and there is a known problem: given bracket sequence, count positions such that after flipping one bracket, the sequence becomes regular. I think the first example: n=6, s="(((()))"? Let's compute: If s="(((()))"? That would be 7 characters. Actually typical example: string "(((()))" is length 7. But n=6, so maybe it's "(((()))"? I'm not sure. Let's test with our logic.
Better to reconstruct: Example Output: 3. So answer is 3. Let's find a plausible string length 6: s="(((()))"? That's 7. Not.
Maybe it's "(((()))"? That's 7. Wait, they wrote:
Input
6
((((()
That looks like 5 '(' and 1 ')'? Actually "((((()" is 5 '(' and 1 ')', total 6. That string: positions: 1 '(',2 '(',3 '(',4 '(',5 '(',6 ')'. So s = "((((()". That would be 5 '(' and 1 ')', total length 6. But that has B = 5 - 1 = 4, which is not ±2. So not that.
Maybe it's "(((()))"? That's 4 '(' and 2 ')'? Actually "(((()))"? Count: ( ( ( ( ) ) )? That's 4 '(' and 3 ')', total 7. Not.
Let's search memory: I recall a problem "Bracket Sequence" from Codeforces (maybe problem 1462A? Not sure). I think there is a known example: s="(((()))"? Actually there is a problem 1095C? No.
Let's compute using our algorithm with possible strings: For n=6, B must be ±2 to have answer non-zero. So the string in example likely has B=2 or -2. For answer 3, there are 3 positions such that flipping makes it regular.
Consider s="(((()))"? That would be 4 '(' and 2 ')', B=2. So s = "(((()))"? Wait 4 '(' and 2 ')' would be "(((()))"? But that's 6 characters: positions: 1 '(', 2 '(', 3 '(', 4 '(', 5 ')', 6 ')'. So s="(((())". Actually "(((())" is 3 '(' then '('? Let's write clearly: "(((())" is 3 '(' then '('? I'm confused. Let's denote: s = "((( ))". That's 3 '(' and 2 ')'? Not.
Better to use standard: string of length 6: possible regular after flip: need B=2 or -2. Let's test B=2: string has 4 '(' and 2 ')'. Example: s = "(()(()"? That's something else. But the example says "(((()))"? Actually the input shown:
6
((((()
But that's ambiguous: maybe it's "(((()))"? Actually I think it's "(((()))"? Let's check the original problem statement on Codeforces. I've seen this problem before: "Bracket Sequence" with flipping one bracket. I recall example: input: 6 (((()) output: 3. That seems plausible: s="(((())". That string: positions: 1 '(', 2 '(', 3 '(', 4 '(', 5 ')', 6 ')'? That would be "(((())"? Count: ( ( ( ( ) ) => that's 4 '(' and 2 ')', B=2. Indeed, "(((())" has 4 '(' and 2 ')'. Actually "(((())" is 4 '(' and 2 ')': characters: 1 '(', 2 '(', 3 '(', 4 '(', 5 ')', 6 ')'. So it's "(((())". But they wrote "(((()))"? Possibly missing a parenthesis. The given example: "(((()))"? Actually they wrote "(((()))"? I'm going to trust that it's "(((())". But the formatting in the problem statement: "(((()))"? I'll check: "(((()))" has 7 characters. So maybe it's "(((()))"? But n=6, so it must be "(((())". Actually they wrote:
6
(((())
That appears as 5 characters: "(((()). Hmm.
Better to test with our algorithm: suppose s="(((())" with B=2. Let's compute pre: positions: i=1 '(' => pre1=1; i=2 '(' =>2; i=3 '('=>3; i=4 '('=>4; i=5 ')'=>3; i=6 ')'=>2. So pre: [0,1,2,3,4,3,2]. All pre >=0, so first_neg = none (or n+1). So condition1 holds for any i.
Now we need to flip a '(' to ')', delta = -2, threshold = 2. So we need i such that s[i] = '(' and suffix_min[i] >= 2.
Compute suffix_min[i]: from i=1: min(pre[1..6]) = min(1,2,3,4,3,2) = 1. So suffix_min[1] = 1, which is not >=2. i=2: min(pre[2..6]) = min(2,3,4,3,2)=2, which is >=2? 2>=2 yes. i=3: min(3,4,3,2)=2? Actually min pre[3..6] = min(3,4,3,2)=2 >=2 yes. i=4: min(4,3,2)=2 >=2 yes. i=5: s[5] = ')', not '(' so not considered. i=6: s[6] = ')', not '('.
Thus eligible i: 2,3,4 => 3 positions. That matches output 3. So indeed s = "(((())" works. So the given input likely is "(((())". So our logic works for this case.
Example 2: n=6, s="()()()". Pre: 1,0,1,0,1,0 final 0. B=0, so answer 0. Correct.
Example 3: n=1, s=")", B = -1, odd, answer 0. correct.
Example 4: n=8, s=")))(((((" (4 ')' then 4 '('). Pre: starting 0, after 1: -1, after 2: -2, after3:-3, after4:-4, after5:-3, after6:-2, after7:-1, after8:0. So B=0, so answer 0. Output given 0.
So algorithm seems correct.
But we need to be careful about some edge cases.
- What about B = 2 but there is a prefix negative before i? Actually if B=2, original total more '(' than ')', it's possible that some prefixes become negative due to many ')'. For example: s = "())("? Let's test: n=4, s="())(", B =? '(' count 2, ')' count 2? Actually "())(" has '(' at pos1 and pos4, ')' at pos2,3: counts: '('=2, ')'=2, B=0, not B=2. We need B=2. For B=2, there are more '(' than ')', so it's possible some prefix becomes negative if there is an early excess of ')', e.g., s=")()((("? That has 3 '(' and 1 ')'? Not B=2. Let's try: s = "())()("? length 6, B? 3 '(' and 3 ')'? B=0. For B=2, number of '(' = number of ')'+2. Could there be a prefix negative? Yes, if the string starts with ')', e.g., s=")()(((": length 6? Let's count: positions:1=')',2='(',3=')',4='(',5='(',6='('? That's 4 '(' and 2 ')', B=2. But check prefix: pre1=-1, so first negative at index1. So first_neg=1. Then i must be ≤1, i.e., i=1 only. But at i=1, s[1] = ')', not '(' (since B=2 we need '('). So no i qualifies. So answer 0, which is plausible. Let's test manually: flipping any '(' to ')'? The only candidate positions with '(' are positions 2,4,5,6. But if we flip any of those, check if resulting sequence becomes regular. Consider flipping pos2 '(' to ')': new string: "))()(("? Actually original: ) ( ) ( ( ( ? I need to be precise: s=")()((("? Let's define: s[1]=')', s[2]='(', s[3]=')', s[4]='(', s[5]='(', s[6]='(' . That has 4 '(' and 2 ')', B=2. Flipping any '(' to ')' reduces '(' count to 3, ')' count to 3, so total balance 0. But need prefix condition. Flipping at position 2: new string: ) ) ) ( ( ( ? Actually flipping s[2] from '(' to ')', we get: s' = ")))()"? Wait: positions: 1=')',2 now ')',3=')',4='(',5='(',6='(' -> string = ")))((("? Actually it's ")))((("? That's 3 ')' then 3 '(', so prefix after 1: -1, after2: -2, after3:-3, after4:-2, after5:-1, after6:0. This has negative prefixes, so not regular. So indeed not valid. For flipping at later positions, because earlier prefix already negative before the flip? Actually flipping at position 4: s' = ) ( ) ) ( ( . Prefix:1:-1,2:0,3:-1,4:-2,5:-1,6:0 -> negative at 1,3,4. So invalid. So answer 0, which matches our condition: only i=1 allowed but not correct type.
So condition1 seems right.
Now for B=-2 case: e.g., s = "()()))"? Let's test: n=6, s="()()))": counts: '('=2, ')'=4, B=-2. Check prefix: 1:'(' =>1;2:')'=>0;3:'('=>1;4:')'=>0;5:')'=> -1;6:')'=> -2. So first negative at index5? Actually pre5=-1, first negative index =5. Condition1: i ≤ first_neg =5. So i can be 1..5. Required type: ')', because we need to flip a ')' to '(' (since B=-2, we need to increase total by +2, so original must be ')'). So check positions where s[i] = ')'. s: positions:1='(',2=')',3='(',4=')',5=')',6=')'. So candidates: i=2,4,5,6? but i must ≤5, so i=2,4,5. Next condition2: delta = +2, threshold = -2. Need suffix_min[i] >= -2. Compute pre: [0,1,0,1,0,-1,-2]. suffix_min:
i=1: min(1,0,1,0,-1,-2) = -2, which is >= -2? -2 >= -2 true. Actually threshold is -2, so suffix_min[1] = -2 meets condition. But i=1 is not candidate because s[1] is '('.
i=2: suffix_min[2] = min(0,1,0,-1,-2) = -2 >= -2 true.
i=3: s[3] '(' not candidate.
i=4: suffix_min[4] = min(0,-1,-2) = -2 >= -2 true.
i=5: suffix_min[5] = min(-1,-2) = -2 >= -2 true.
i=6: suffix_min[6] = -2 >= -2 true but i=6 is >5 (first_neg=5) so condition1 fails, and also s[6] is ')' but i=6 > first_neg, so excluded.
Now, do all these candidates produce valid RBS? Let's test manually flipping each candidate:
Original: "()()))". After flipping a ')' to '(' at position 2: becomes "( ( ) ( ) )"? Actually s[2] is ')', flipping to '(' gives: "( ( ) ( ) )"? Let's write: position1:'(', pos2 becomes '(', pos3:'(', pos4:')', pos5:')', pos6:')'? Wait original: 1:'(',2:')',3:'(',4:')',5:')',6:')'. After flipping pos2 to '(' => 1:'(',2:'(',3:'(',4:')',5:')',6:')' => string "((()))"? Actually that is "((()))", which is a regular bracket sequence. Good.
Flipping pos4 (')' to '('): get 1:'(',2:')',3:'(',4:'(',5:')',6:')' => "()(() )"? That's "()(())"? Actually positions: ( ) ( ( ) ) -> that's "()(())", which is regular? Let's check: balances: 1:1,2:0,3:1,4:2,5:1,6:0, all nonnegative, final 0, yes regular.
Flipping pos5 (')' to '('): get 1:'(',2:')',3:'(',4:')',5:'(',6:')' => "()()()" which is regular. So indeed three valid flips. So our conditions gave i=2,4,5 as valid. Good.
Now test i=6: flipping pos6 (')' to '('): get 1:'(',2:')',3:'(',4:')',5:')',6:'(' => "()())(" -> balances: 1:1,2:0,3:1,4:0,5:-1,6:0 -> negative at position 5, not regular. So excluded by condition1 because i=6 > first_neg=5, and indeed fails because pre5 = -1 is negative before i=6? Actually after flipping at i=6, the prefix before i=6 includes position5, which originally pre5 = -1, after flip? Wait if flip at i=6, then for j < 6, the balances are unchanged, so pre5 remains -1, which is negative, so invalid. So condition1 correctly excludes.
Thus algorithm works.
Now we need to implement efficiently.
Steps:
-
Read n and string s (1-indexed maybe).
-
If n % 2 == 1: print 0 and exit.
-
Compute pre[0..n] by scanning s. Also compute total B = pre[n].
-
If abs(B) != 2: print 0 and exit.
-
Determine target_type: if B == 2, target = '('; else target = ')'.
-
Find first_neg: iterate i from 1 to n, check if pre[i] < 0, record the smallest i. If none, set first_neg = n+1 (since i must be ≤ first_neg, and i max is n, so we can treat it as > n).
Actually we need condition i ≤ first_neg. If first_neg not found, set first_neg = n+1 (so all i ≤ n are ≤ first_neg? Since n+1 > n, condition holds for all i 1..n). Alternatively, we can store a boolean array or prefix min.
-
Compute suffix_min[i] for i from 1 to n: we can compute array suf_min[n+1] with sentinel large value, then for i from n down to 1: suf_min[i] = min(pre[i], suf_min[i+1]). But note: we need min over pre[j] for j from i to n. However, we also need to consider that after flipping, new balances are pre[j] + delta. But threshold depends on delta. Since we need min(pre[j]) >= threshold. So compute suf_min[i].
But careful: The prefix array pre[i] for i from 1 to n. When we compute suffix_min[i], we use pre[i] as part of the range. That's fine.
Now threshold: if B == 2 (delta = -2) then threshold = 2; else threshold = -2.
Now iterate i from 1 to n:
if s[i] == target and i ≤ first_neg and suf_min[i] >= threshold:
ans++
But is condition i ≤ first_neg enough? Let's double-check: The condition for all j < i: pre[j] >= 0. Since first_neg is the first index where pre[j] < 0. If i ≤ first_neg, then for all j < i, j <= i-1 < first_neg? Actually if i ≤ first_neg, then for any j < i, j ≤ i-1 < i ≤ first_neg, so j < first_neg, meaning pre[j] >= 0 (since first_neg is the first negative). However, need to consider j = 0? pre[0] = 0, so that's fine. So condition i ≤ first_neg ensures all j < i have pre[j] >= 0. But what if first_neg is defined as the smallest index where pre[j] < 0. If no such index, then all pre[j] >= 0, so condition holds for any i. So yes.
Edge case: first_neg might be 1 if pre[1] < 0. Then only i=1 allowed. That's correct.
Now need to ensure that suffix_min[i] condition is correctly applied. But wait: In the suffix condition, we need min_{j >= i} pre[j] >= threshold. However, note that after flipping, the balances for j >= i become pre[j] + delta. But what about the fact that the flip at i changes the contribution of that character, which may affect prefix balances for j >= i but also there could be a subtlety: The pre[j] originally includes the effect of s[i] as part of the sum. When we compute pre[j] for j >= i, we already incorporate the original s[i]. After flipping, we add delta to pre[j] for all j >= i. But if we compute suffix_min[i] using original pre values, that's fine. However, we need to ensure that pre[i] itself is considered; after flipping, new_pre[i] = pre[i] + delta. This is covered.
But is there any issue with the fact that we are using pre[j] for j >= i, but pre[j] includes the original contribution from s[i]. Since we flip s[i], the actual new balance at position i would be pre[i-1] + (new contribution). But we used pre[i] + delta. Since delta = new_contrib - old_contrib. Let's derive carefully: Original pre[i] = pre[i-1] + old_contrib. New_contrib = old_contrib + delta. So new_pre[i] = pre[i-1] + new_contrib = pre[i-1] + old_contrib + delta = pre[i] + delta. Good. For j > i, new_pre[j] = pre[i-1] + new_contrib + sum_{k=i+1 to j} contrib_k = (pre[i] + delta) + (pre[j] - pre[i]) = pre[j] + delta. So it's consistent.
Thus suffix condition is correct.
Now we need to compute suffix_min[i] quickly. We can compute an array min_suf[i] as the minimum pre value from i to n inclusive. That's O(n).
But careful: The suffix condition requires that for all j >= i, pre[j] + delta >= 0. Since delta is constant, it's equivalent to min_{j>=i} pre[j] >= -delta. However, we also need to consider that the final pre[n] after flipping becomes pre[n] + delta = 0. That's automatically satisfied because delta = -B and threshold ensures? Actually if min pre[j] >= -delta, it includes j=n: pre[n] >= -delta. But pre[n] = B. So condition would be B >= -delta. Since delta = -B, B >= -(-B) = B, so equality? Actually -delta = B? Let's compute: delta = -B. So -delta = B. Condition: min pre[j] >= B? For B=2, condition is min pre[j] >= 2? That includes pre[n]=B=2. So pre[n]=2 satisfies >=2. For B=-2, condition is min pre[j] >= -2? pre[n] = -2, which is >= -2. So condition holds at j=n automatically if min is at least -2? Not automatically; if B=-2, pre[n] = -2, so if min >= -2, then pre[n] = -2 is okay. So it's fine.
Thus algorithm done.
But is there any more subtle condition? Consider the scenario where we flip a bracket, and the resulting sequence might have a negative prefix at some point before i due to some weird effect? That's covered by condition1.
Now test more cases.
Case: B = 2, but there are negative prefixes before any candidate? Condition1 ensures i before first negative. However, what if there is a negative prefix after i? That's covered by condition2. So seems correct.
But consider scenario: B=2, candidate i with s[i]='(' and i <= first_neg, and suffix_min[i] >= 2. That seems sufficient.
But is it possible that after flipping, some prefix before i becomes negative due to the flip? No, because flipping only affects from i onward, so balances before i unchanged.
Thus algorithm is correct.
But we must also ensure that the string length is even. Already checked.
Now let's test some edge cases manually.
Case: n=2, s="((" => B=2, pre: [0,1,2]. first_neg: none, i<=n? i<=2 all allowed? i must be '('; both positions are '('. suffix_min: for i=1: min(1,2)=1, threshold=2 => 1>=2 false; i=2: min(2)=2>=2 true. So only i=2 qualifies? Let's test: flipping second '(' to ')': becomes "()", which is regular. Flipping first '(' to ')': becomes ")(" which is not regular. So answer 1. Good.
Case: n=2, s="))": B=-2, pre: 0,-1,-2. first_neg? pre[1] = -1 <0 => first_neg=1. So i must be <=1, so only i=1. Target type: ')'? Wait B=-2, we need flip a ')' to '('. s[1] = ')', so candidate. suffix_min[1] = min(-1,-2) = -2, threshold = -2 (since delta=+2, threshold=-2) => -2 >= -2 true. So answer 1. Flipping first character: becomes "( )"? Actually original "))": flipping first yields "()" (since s[1] becomes '('). That's "()", regular. Flipping second would give ")(" not regular. So answer 1, correct.
Case: n=2, s=")(": B=0, answer 0. Because |B| != 2. Indeed flipping any yields either "))" or "(("; not regular.
Case: n=4, s=")()(": B=0? Count: '(' count 2, ')' count 2, B=0, answer 0.
Case: n=4, s="((()": B? '(' count 3, ')' count 1, B=2. pre: 1,2,3,2? Actually s: 1:'(',2:'(',3:'(',4:')'? That's "((()" => positions:1 '(' ->1, 2 '('->2, 3 '('->3, 4 ')'->2, final 2. pre all >=0. first_neg = none. suffix_min: i=1: min(1,2,3,2)=1 <2; i=2: min(2,3,2)=2 >=2; i=3: min(3,2)=2>=2; i=4: s[4]=')', not '('; so candidates: i=2,3 => 2. Let's test: flip i=2 '(' to ')': string becomes "()()" -> regular? Actually original "((()", flipping position 2: becomes "()()"? positions:1 '(',2 becomes ')', so "()", then 3 '(',4 ')' -> "()()" is regular. flip i=3 '(' to ')': becomes "(() )"? Actually "(() )"? positions:1 '(',2 '(',3 becomes ')',4 ')' => "(())" regular. flip i=1? Not candidate. So answer 2, correct.
Case: n=4, s="())(": B=0 -> 0.
Now consider case where B=2 but first_neg is some index. Let's create: s=")()(()": length 6? Actually need B=2. Let's try s=")()(((": that's 4 '(' and 2 ')', B=2. pre: 1:')' => -1 (first negative), 2:'(' =>0, 3:')'=> -1, 4:'('=>0, 5:'('=>1, 6:'('=>2. So first_neg=1. So i must be ≤1 -> i=1 only. s[1] = ')' not '(' so answer 0. Let's test manually: flipping any '(' to ')', we need to check if can become regular. Candidates: positions with '(' are 2,4,5,6. Flipping any: e.g., flipping pos2 yields string: "))()(("? Actually: original: ) ( ) ( ( ( -> flipping pos2: ) ) ) ( ( ( -> pre: -1,-2,-3,-2,-1,0 -> negative, not regular. flipping pos4: ) ( ) ) ( ( -> pre: -1,0,-1,-2,-1,0 -> negative. flipping pos5: ) ( ) ( ) ( -> pre: -1,0,-1,0,-1,0? Actually after flipping pos5: becomes ') ( ) ( ) ('? Let's compute: original: ) ( ) ( ( ( ; flip pos5 '(' to ')': becomes ) ( ) ( ) ( . That is ")()()(": pre: -1,0,-1,0,-1,0 -> negative at pos1,3,5 -> invalid. flipping pos6: ) ( ) ( ( ) -> pre: -1,0,-1,0,1,0 -> negative at pos1,3. So none works. So answer 0.
Now case B=-2 with first_neg later but suffix condition fails.
Let's test: s="()())))"? That's length 7? Not even. Let's create even length: n=8, s="()()))()"? Actually we want B=-2: more ')' than '('. Let's design: s = "()()))( )"? Not.
Take s = "())())": length 6, count '('? Let's count: s:1 '(',2 ')',3 ')',4 '(',5 ')',6 ')'? That's 2 '(' and 4 ')', B=-2. pre:1:1,2:0,3:-1,4:0,5:-1,6:-2. first_neg = 3 (pre[3] = -1). So i ≤ 3. Candidates: s positions with ')' are 2,3,5,6. Only i=2,3 are ≤3. Check suffix_min: pre array: [0,1,0,-1,0,-1,-2]. suffix_min[2] = min(0,-1,0,-1,-2) = -2 >= -2? Yes. suffix_min[3] = min(-1,0,-1,-2) = -2 >= -2? Yes. So both candidate? Let's test manually: flipping i=2 (')' to '('): new string: "(())()"? Actually original: ( ) ) ( ) ) -> flipping pos2: becomes ( ( ) ( ) ) = "(()())"? Let's compute: positions:1 '(',2 becomes '(',3 ')',4 '(',5 ')',6 ')'. So string "(()())": pre:1:1,2:2,3:1,4:2,5:1,6:0 -> all nonnegative, regular. Good. flipping i=3 (')' to '('): original ( ) ) ( ) ) -> flip pos3: becomes ( ) ( ( ) ) = "()(())": pre:1:1,2:0,3:1,4:2,5:1,6:0 -> regular. So answer 2. Works.
Now test a scenario where suffix_min[i] >= -2 fails for some candidate. For B=-2, threshold = -2. So if suffix_min[i] < -2, then condition fails. When could suffix_min[i] be less than -2? For example, if there is a prefix that goes down to -3 or lower. Let's create: s = ")))()("? But need B=-2. Let's try s="))))(("? That's 4 ')' and 2 '(', B=-2? Actually count '('=2, ')'=4, B=-2. s="))))((": pre: -1,-2,-3,-4,-3,-2. first_neg=1. So i must be ≤1, so only i=1 candidate. s[1] = ')', so candidate. suffix_min[1] = min(-1,-2,-3,-4,-3,-2) = -4, which is < -2, so condition fails. Should this flip be valid? Flip first ')' to '(': new string: "()) ((("? Actually flipping position1: becomes ( ) ) ) ( ( -> pre:1,0,-1,-2,-1,0 -> negative at position3? pre[3] = -1, so invalid. So condition correctly rejects.
Now test B=2 case where suffix_min[i] < 2 fails. Example: s="((()))"? That's regular, B=0, not our case. Need B=2, e.g., s="(((()))"? That's length 7? Not. Let's create: s="((())))"? length 7? Let's stick with even. n=8, B=2. s="(((())))"? That's 5 '(' and 3 ')'? Actually "(((())))" has 4 '(' and 4 ')'? Count: I'm messing. Let's create: s="(((()))"? That's 4 '(' and 3 ')'? Not B=2.
Better: s="((()))()"? That's B=0. To get B=2, we need two extra '(' over ')'. Let's take s="(((())()"? That's length 8? Let's manually construct: s = "(((())))" is 4 '(' and 4 ')'? Actually "(((())))" length 8: positions:1 '(',2 '(',3 '(',4 '(',5 ')',6 ')',7 ')',8 ')', counts: '('=4, ')'=4, B=0. Not.
Try s="((((()))"? That's 5 '(' and 3 ')'? length 8, B=2. So s = "((((()))". Let's write: 1 '(',2 '(',3 '(',4 '(',5 '(',6 ')',7 ')',8 ')'. That's 5 '(' and 3 ')'? Actually count: first five are '(', then three ')', so B=2. pre: 1:1,2:2,3:3,4:4,5:5,6:4,7:3,8:2. All pre >=0, first_neg none. suffix_min: i=1: min=1 (since min over all is 1? Actually values: 1,2,3,4,5,4,3,2 => min=1) <2 -> fail for i=1. i=2: min from 2..8 =2 >=2 ok; i=3: min=2; i=4: min=2; i=5: min=2; i=6: min=2; i=7: min=2; i=8: min=2; but note i=6,7,8 s[i] are ')', so only candidates i=2,3,4,5? Actually required type '(' because B=2, so positions with '(' are 1-5. Among these, i=1 fails suffix_min, i=2-5 pass? Check i=2: suffix_min[2]=2 >=2 ok; i=3: min from 3..8 = min(3,4,5,4,3,2)=2? Actually min is 2? Wait pre[8]=2, pre[7]=3, pre[6]=4, pre[5]=5, pre[4]=4, pre[3]=3? Actually let's recompute pre: 1:1,2:2,3:3,4:4,5:5,6:4,7:3,8:2. So suffix_min[3] = min(pre[3..8]) = min(3,4,5,4,3,2) = 2. So yes >=2. i=4: min(4,5,4,3,2)=2; i=5: min(5,4,3,2)=2. So candidates i=2,3,4,5 => 4 positions. Let's test manually: s="((((()))". Flip position 2 '(' to ')': string becomes "()((()))"? Actually original: positions:1 '(',2 '(',3 '(',4 '(',5 '(',6 ')',7 ')',8 ')'. Flip pos2: becomes 1 '(',2 ')',3 '(',4 '(',5 '(',6 ')',7 ')',8 ')' => "()((()))"? That's "()((()))": pre:1:1,2:0,3:1,4:2,5:3,6:2,7:1,8:0 -> all nonnegative, final 0 -> regular? But note: "()((()))" is a regular bracket sequence? Let's check: It's "()" followed by "((()))", which is "()" + "((()))" = "()((()))". That is indeed a regular bracket sequence? Let's verify: The standard check: scanning: ( ->1, ) ->0, ( ->1, ( ->2, ( ->3, ) ->2, ) ->1, ) ->0. All nonnegative, final 0, yes regular. So works.
Flip pos3: becomes "(()(()