Flipping Parentheses
Time limit5sMemory limit256 MB
After each single-bracket flip that breaks a balanced parenthesis string, find the leftmost second flip that restores balance.
- Level
Medium7 of 10
- Topics
- Segment tree, Prefix sum
- Solved
- No attempts yet
Problem
A string made only of ( and ) is called balanced if it satisfies one of the following conditions.
- The string
()is balanced. - The concatenation of two balanced strings is balanced.
- If a string is balanced, then the concatenation of
(, , and)in this order is balanced.
This condition is stronger than requiring equal counts of ( and ). For example, ())(() has three of each but is not balanced.
Your task is to keep a string balanced in a harsh setting where a cosmic ray may flip the direction of a parenthesis.
You are given a balanced string at the start. Each time the direction of a single parenthesis is flipped, your program is told the position of the changed character. You then compute and output the leftmost position such that flipping the parenthesis there makes the whole string balanced again. After the string is balanced by flipping the parenthesis your program reported, the next cosmic ray flips another parenthesis, and the same steps repeat several times.
Input
The input consists of a single test case in the following format.
N Q
s
q1
.
.
.
qQ
The first line contains two integers and (, ). The second line contains a balanced parenthesis string of length . Each of the following lines contains an integer (), which means that the direction of the -th parenthesis is flipped.
Output
For each event , output on its own line the leftmost position of a parenthesis you have to flip to get back to the balanced state. Such a position always exists.
Each event applies to the string after the previous event and its fix.
Notes
In the first example the initial state is ((())). The 4th parenthesis is flipped and the string becomes (((()). To restore the balance you flip the 2nd parenthesis and get ()(()). The next flip, of the 3rd parenthesis, applies to that last state and yields ())()). Changing the 2nd parenthesis once more gives (()()), which is balanced.