Flipping Brackets

3

2 votes
Advanced Data Structures, Algorithms, Data Structures, Graphs, Medium, Segment Trees, Sorting
Problem

A regular bracket sequence is a sequence of '(' and ')' characters defined as follows:

  • The empty string (without any characters) is a regular bracket sequence.
  • If A is a regular bracket sequence, then (A) is also considered a regular sequence.
  • If A and B are regular bracket sequences, then AB is also considered as a regular bracket sequence.

For a string S that consists of only '(' and ')' characters, consider a sequence of M operations that are of one of the following types:

  • C i: If the character Si is an opening bracket '(' , then it is replaced by a closing bracket ')'. Similarly, the ')' character is replaced by the '(' character.
  • Q i: Determine the maximum length K of the regular bracket sequence starting at index i of the string. Formally, the string Si Si+1... Si+K1 should be a regular bracket sequence, where K is maximized. If there is no regular bracket sequence starting at index i, then print 0.

Input format

  • First line: String S
  • Next line: M representing the number of queries
  • Next M lines: A query of the following types:
    • C i
    • Q i

Output format

For the query of the type Q , print the length of the longest regular bracket sequence starting at index i.

Input Constraints

1|S|2×105

1M2×105

1iqueryN

Sample Input
(()((())
11
C 7
Q 4
Q 4
Q 1
C 6
C 7
Q 1
C 1
C 1
Q 1
Q 4
Sample Output
0
0
0
8
8
4
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

After every query:

  • 0 (Initial String): (()((())
  • 1(()(((()
  • 2: There exists no regular bracket sequence starting at index 4
  • 3: There exists no regular bracket sequence starting at index 4
  • 4: There exists no regular bracket sequence starting at index 1
  • 5: (()(()()
  • 6: (()(()))
  • 7: The whole string is a regular bracket sequence, hence answer = 8 from index 1.
  • 8)()(()))
  • 9(()(()))
  • 10: The whole string is a regular bracket sequence, hence answer = 8 from index 1.
  • 11: Answer = 4, corresponding to: (()(()))
Editor Image

?