Title: http://poj.org/problem?id=1141
Interval DP + constructs the solution of DP
Here are two ways of thinking are right:
The first (recommended): Dp[i][j]: = Interval i~j minimum number of characters required to match parentheses, and then construct a DP solution.
The second: dp[i][j]: = Interval i~j The length of the oldest sequence that matches the parentheses, and then, in the process of constructing the oldest sequence, the characters themselves are already matched, and then the rest is complete.
The first type:
#include <cstdio>#include<iostream>#include<cstring>#include<string>using namespacestd;Chars[ the];intdp[ the][ the];intc[ the][ the];voidDfsintIintj) { if(I>Jreturn; if(C[i][j] = =-1) { if(S[i] = ='['|| S[i] = =']') printf ("%s","[]"); Elseprintf"%s","()"); DFS (i+1, J); } Else { intK =C[i][j]; printf ("%c", S[i]); DFS (i+1, K-1); printf ("%c", S[k]); DFS (k+1, J); }}intMain () {scanf ("%s", s); intLen =strlen (s); for(intstep=0; step<len; step++) { for(intI=0; i+step<len; i++) { intj = i +step; DP[I][J]= dp[i+1][j]+1; C[I][J]= -1; for(intk=i+1; k<=j; k++) { if(s[i]=='('&& s[k]==')'|| s[i]=='['&& s[k]==']') { if(dp[i+1][k-1]+dp[k+1][J] <Dp[i][j]) {Dp[i][j]= dp[i+1][k-1]+dp[k+1][j]; C[I][J]=K; } } } } }//printf ("%d\n", dp[0][len-1]);Dfs0, len-1); printf ("\ n"); return 0; }
The second type:
#include <cstdio>#include<iostream>#include<cstring>#include<string>using namespacestd;Chars[ the];intdp[ the][ the], c[ the][ the];BOOLvis[ the];voidDfsintIintj) { if(I>=J)return; if(c[i][j]==-1) DFS (i+1, J); Else { intK =C[i][j]; Vis[i]= Vis[k] =1; DFS (i+1, K-1); DFS (k+1, J); }}intMain () {scanf ("%s", s); intLen =strlen (s); for(intstep=1; step<len; step++) { for(intI=0; i+step<len; i++) { intj = i +step; DP[I][J]= dp[i+1][j]; C[I][J]= -1; for(intk=i+1; k<=j; k++) { if(s[i]=='('&& s[k]==')'|| s[i]=='['&& s[k]==']') { if(dp[i+1][k-1]+dp[k+1][j]+2>Dp[i][j]) {Dp[i][j]= dp[i+1][k-1]+dp[k+1][j]+2; C[I][J]=K; } }}}} DFS (0, len-1); for(intI=0; i<len; i++) { if(Vis[i]) {printf ("%c", S[i]); } Else { if(S[i] = ='['|| S[i] = =']') printf ("%s","[]"); Elseprintf"%s","()"); }} printf ("\ n"); return 0; }
POJ 1141--brackets Sequence