1791 Valid Bracket sub-paragraph
Description
there is a sequence of parentheses, and now it's time to calculate how many of the non-empty segments are valid bracket sequences.
the definition of a valid bracket sequence is:
1. The empty sequence is the valid bracket sequence.
2. If s is the valid bracket sequence, then (s) is the valid bracket sequence.
3. If A and B are both valid parentheses, then AB is the valid 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 line, each row has a sequence of parentheses, which is a non-empty string composed of ' (' and ') '. the total length of all entered brackets is no more than 1100000. output t row, each row corresponds to the answer to a test data. Input Sample
5
(
()
()()
(()
(()) output Sample
0
1
3
1
2 Solution
A magical DP problem, in fact, is also very good, because for each of them ' (' can only find a match ') '. Obviously, in the case where the bracket string is fixed, the parentheses match is fixed. With this strategy, we can first use the stack to match the parentheses, P[i] represents the position of the brackets matching the I bracket, easy to get the DP equation ans[i]=ans[p[i]+1]+1, and then the line sweep the sum.
#include <cstdio> #include <algorithm> #include <cstring> using namespace
Std
int t,p[1100010],stuck[1100010],ans[1100010];
Char ch[1100010];
int main () {scanf ("%d", &t);
while (t--) {scanf ("%s", ch+1);
int L=strlen (ch+1), top=0;
Long Long num=0;
for (int i=1;i<=l;i++) p[i]=-1;
for (int i=1;i<=l;i++) {if (ch[i]== ') stuck[++top]=i;
else if (top) p[stuck[top--]]=i; for (int i=l;i>=1;i--) if (p[i]==-1) ans[i]=0;
else ans[i]=ans[p[i]+1]+1;
for (int i=1;i<=l;i++) num+=ans[i];
printf ("%lld\n", num);
return 0; }