Description
There is a sequence of parentheses, and now it is time to calculate how many of the non-empty segments it has is a valid bracket sequence.
The legal bracket sequence is defined as: An empty sequence is a valid bracket sequence. If S is a valid bracket sequence, then (s) is the legal bracket sequence. If both a and B are valid bracket sequences, then AB is the legal bracket sequence.
Input
Multiple sets of test data.
The first line has an integer T (1<=t<=1100000) that represents the number of test data.
Next T, each line has a sequence of parentheses, which is a non-empty string consisting of ' (' and ') '.
The total length of all input bracket sequences does not exceed 1100000.
Output
Output T line, each line corresponds to the answer to a test data.
Input Example
5 (() () () () (() (() (
()
)
Output Example
0
1
3)
1
2
Ideas
The position of the closing parenthesis corresponding to each opening parenthesis is preprocessed first, and Cnt[i]=j Cnt[i]=j represents the position of the closing parenthesis for the opening parenthesis I I, which is J J.
Dp[i] Dp[i] represents the number of valid bracket sequences on the right side of I I.
For each opening parenthesis, dp[i]=dp[cnt[i]+1]+1 dp[i]=dp[cnt[i]+1]+1, which indicates the number of valid parenthesis sequences on the right side of each opening parenthesis equals the left parenthesis (if any) adjacent to the right parenthesis of the current match, plus the number of the current pair.
AC Code
#include <bits/stdc++.h> using namespace std; #define INF 0x3f3f3f3f const int MAXN = 12000
00;
const int mod = 1E9+7;
typedef long Long LL;
Stack<int> SK;
int CNT[MAXN];
LL ANS[MAXN];
Char STR[MAXN];
void Solve () {while (!sk.empty ()) Sk.pop ();
int len = strlen (str);
for (int i=0; i<=len+1; i++) {ans[i] = 0;
Cnt[i] =-1;
} for (int i=len-1; i>=0; i--) {if (str[i]== ') ') Sk.push (i);
else {if (Sk.empty ()) continue;
Cnt[i] = Sk.top ();
Sk.pop ();
}} LL res = 0;
for (int i=len-1; i>=0; i--) {if (cnt[i]!=-1) {ans[i] = ans[cnt[i]+1]+1;
Res + = Ans[i];
}} printf ("%lld\n", res);
} int main () {int T;
scanf ("%d%*c", &t);
while (t--) {scanf ("%s", str);
Solve (); }
}