Topic Links:
http://hihocoder.com/problemset/problem/1300
Exercises
Use the stack to preprocess each ') ' matched ' (' seat, placed in the POS array.
Dp[i] Indicates the number of valid substrings ending with I, then the transfer equation is easy to know:
dp[i]=dp[pos[i]-1]+1;
Code:
#include <iostream>#include<cstdio>#include<stack>using namespaceStd;typedefLong LongLL;Const intMAXN = 1e6 +Ten;CharSTR[MAXN]; LL DP[MAXN];intPOS[MAXN];voidinit () {memset (pos,0,sizeof(POS)); Memset (DP,0,sizeof(DP));}intMain () { while(SCANF ("%s", str +1) ==1) { intlen = strlen (str +1); Init (); Stack<int>MS; for(inti =1; I <= Len; i++) { if(Str[i] = ='(') {Ms.push (i); } Else { if(!Ms.empty ()) { intj =ms.top (); Ms.pop (); Pos[i]=J; }}} LL ans=0; for(inti =1; I <= Len; i++) { if(pos[i]>=1) Dp[i] = dp[pos[i]-1] +1; Ans+=Dp[i]; } printf ("%lld\n", ans); } return 0;}
Hihocoder #1300: Carp flag DP at the exhibition resort