[Solution] Bracket Cost Codeforces Solution
Daemon Targaryen decided to stop looking like a Metin2 character. He turned himself into the most beautiful thing, a bracket sequence.
For a bracket sequence, we can do two kind of operations:
- Select one of its substrings and cyclic shift it to the right. For example, after a cyclic shift to the right, "(())" will become ")(()";
- Insert any bracket, opening '(' or closing ')', wherever you want in the sequence.
We define the cost of a bracket sequence as the minimum number of such operations to make it balanced.
Given a bracket sequence of length , find the sum of costs across all its non-empty substrings. Note that for each substring we calculate the cost independently.
A string is a substring of a string if can be obtained from by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters and . For example, sequences "(())()", "()", and "(()(()))" are balanced, while ")(", "(()", and "(()))(" are not.
Each test consists of multiple test cases. The first line contains a single integer () — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer () — the length of the bracket sequence.
The second line of each test case contains a string , consisting only of characters '(' and ')', of length — the bracket sequence.
It is guaranteed that sum of across all test cases does not exceed .
For each test case, print a single integer — the sum of costs of all substrings of .
In the first test case, there is the only substring ")". Its cost is because we can insert '(' to the beginning of this substring and get a string "()", that is a balanced string.
In the second test case, the cost of each substring of length one is . The cost of a substring ")(" is because we can cyclically shift it to right and get a string "()". The cost of strings ")()" and "()(" is because its enough to insert one bracket to each of them. The cost of substring ")()(" is because we can cyclically shift it to right and get a string "()()". So there are substring of cost and substring of cost . So the sum of the costs is .
In the third test case,
- "(", the cost is ;
- "()", the cost is ;
- "())", the cost is ;
- ")", the cost is ;
- "))", the cost is ;
- ")", the cost is .
So the sum of the costs is
No comments:
Post a Comment