This problem is an introduction to the interval DP. The title asks for the longest valid parenthesis sequence length, the direct memory searches the words to be good to think, but the code is a bit long, if writes the recursive type then the code will be reduced much.
State transition equation:
DP[I][J] indicates the longest length from I to J can be composed
If I position and J position pair, then dp[i][j] = Dp[i + 1][j-1] + 2;
The next step is to enumerate k,k from the position between i-j, dp[i][j] = min (dp[i][k]+dp[k + 1][j]), even if the pairing is met, as it is possible to "() ()".
The code is as follows:
#include <cstdio>#include<iostream>#include<cstring>#include<cmath>#include<cstdlib>#include<algorithm>using namespaceStd;typedefLong Longll;Const intMAXN = the;CharS[MAXN];intD[MAXN][MAXN];BOOLMatchCharACharb) { return(A = ='('&& b = =')'|| A = ='['&& b = =']');}intMain () { while(Cin >> S && strcmp (s),"End") !=0) {memset (d,0,sizeof(d)); intLen =strlen (s); for(intL =1; L <= Len; l++) { for(inti =0; i + L-1< Len; i++) { intj = i + L-1; if(Match (S[i], s[j])) D[i][j]= D[i +1][j-1] +2; for(intK = i; K < J; k++) D[i][j]= Max (D[i][j], d[i][k] + d[k +1][j]); }} printf ("%d\n", d[0][len-1]); } return 0;}
View Code
POJ 2955 Brackets (interval dp)