Subject address: Ural 1183
Finally, I gave this question to... Dragging for a long time ,..
I can't think of it myself. This is exactly the answer in the purple book.
D [I] [J] indicates the minimum number of parentheses required for the input sequence from subscript I to subscript J to become a valid sequence. 0 <= I <= j <Len (Len is the length of the input sequence ).
C [I] [J] is the disconnection position from subscript I to subscript J of the input sequence. If not, it is-1.
When I = J, d [I] [J] is 1
When s [I] = '(' & S [J] = ') 'or s [I] =' ['& S [J] =, d [I] [J] = d [I + 1] [J-1]
Otherwise, d [I] [J] = min {d [I] [k] + d [k + 1] [J]} I <= k <J, c [I] [J] records the disconnected location K
Recursive calculation of d [I] [J]
Print (0, len-1) is output recursively)
The output function is defined as print (int I, Int J), which indicates that the valid sequence from subscript I to subscript J is output.
When I> J, it is returned directly without output.
When I = J, d [I] [J] is 1, and at least a bracket must be added. If s [I] is '(' or ')', output "()"; otherwise, output "[]".
When I> J, if C [I] [J]> = 0, it indicates that from I to J is disconnected, print (I, c [I] [J]); and print (C [I] [J] + 1, J );
If C [I] [J] <0, it indicates that it is not disconnected, if s [I] = '(' Then output' (', print (I + 1, J-1 ); and ")"
Otherwise output "[" Print (I + 1, J-1); and "]"
The Code is as follows:
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;#define LL __int64const int INF=0x3f3f3f3f;char s[200];int dp[110][110], tag[110][110];int match(char c1, char c2){ if((c1=='('&&c2==')')||(c1=='['&&c2==']')) return 1; return 0;}void print(int l, int r){ if(l>r) return ; if(l==r) { if(s[l]=='('||s[l]==')') printf("()"); else printf("[]"); } else if(tag[l][r]==-1) { printf("%c",s[l]); print(l+1,r-1); printf("%c",s[r]); } else { print(l,tag[l][r]); print(tag[l][r]+1,r); }}int main(){ int n, m, i, j, len, k; gets(s); len=strlen(s); if(len==0) { puts(""); } memset(dp,INF,sizeof(dp)); memset(tag,-1,sizeof(tag)); for(i=0;i<len;i++) { dp[i][i]=1; dp[i+1][i]=0; } for(i=len-2;i>=0;i--) { for(j=i+1;j<len;j++) { dp[i][j]=len+1; if(match(s[i],s[j])) { dp[i][j]=min(dp[i][j],dp[i+1][j-1]); } for(k=i;k<=j;k++) { if(dp[i][j]>dp[i][k]+dp[k+1][j]) { dp[i][j]=dp[i][k]+dp[k+1][j]; tag[i][j]=k; } } } } //printf("%d\n",dp[0][len-1]); /*for(i=0;i<4;i++) { for(j=0;j<4;j++) { printf("%d ",tag[i][j]); } puts(""); }*/ print(0,len-1); puts(""); return 0;}
Ural 1183 brackets sequence (interval DP + memory-based search)