Balanced Rainbow Sequence
Time limit2sMemory limit512 MB
Flip the fewest brackets so that the sequence stays balanced after removing all lime brackets and after removing all gray brackets.
- Level
Hard8 of 10
- Topics
- Dynamic programming, String, Prefix sum
- Solved
- No attempts yet
Problem
Lewin and Gan have a parentheses sequence. Nah, that word is clumsy as hell. Okay, one more time:
You are given a bracket sequence. Each bracket has one of 3 colors: lime, gray and blue and is either opening or closing.
You are allowed to change some brackets from opening to closing and vice versa. You are not allowed to change the order or colors of brackets. You want to do zero or more changes such that the resulting sequence satisfies the following:
- If all the lime brackets are removed, the remaining brackets form a balanced bracket sequence.
- If all the gray brackets are removed, the remaining brackets form a balanced bracket sequence.
A bracket sequence is balanced if it satisfies one of the following conditions:
- is empty.
- , where both and are non-empty balanced bracket sequences.
- , where is a balanced bracket sequence. Note that the starting opening brace and the trailing closing brace may have different colors.
Is it possible to do so and if it is, what is the minimum number of changes you have to make?
Input
The first line contains a single integer (), the length of the bracket sequence.
The second line contains a string of length consisting of characters "(" and ")", the bracket sequence.
The third line contains integers (). denotes the color of the -th bracket. corresponds to lime, to gray and to blue.
Output
Print a single integer, the minimum number of changes you have to make if it is possible to satisfy the conditions, and -1 otherwise.
Hint
In the first example a possible resulting sequence is (()().