G - Brackets Sequence POJ - 1141 (動態規劃)
G - Brackets Sequence
Let us define a regular brackets sequence in the following way:
1. Empty sequence is a regular sequence.
2. If S is a regular sequence, then (S) and [S] are both regular sequences.
3. If A and B are regular sequences, then AB is a regular sequence.
For example, all of the following sequences of characters are regular brackets sequences:
(), [], (()), ([]), ()[], ()[()]
And all of the following character sequences are not:
(, [, ), )(, ([)], ([(]
Some sequence of characters '(', ')', '[', and ']' is given. You are to find the shortest possible regular brackets sequence, that contains the given character sequence as a subsequence. Here, a string a1 a2 ... an is called a subsequence of the string b1 b2 ... bm, if there exist such indices 1 = i1 < i2 < ... < in = m, that aj = bij for all 1 = j = n.
Input
The input file contains at most 100 brackets (characters '(', ')', '[' and ']') that are situated on a single line without any other characters among them.
Output
Write to the output file a single line that contains some regular brackets sequence that has the minimal possible length and contains the given sequence as a subsequence.
Sample Input
([(]
Sample Output
()[()]
動態規劃,用dp[i][j]儲存從第i個字元(從零開始算)到第j個字元間形成完整regular sequences需要新增的字元個數,pos[i][j]表示形成第i個字元(從零開始算)到第j個字元間形成完整regular sequences需要斷開而形成的題目所說的AB的形式的分界點(該點為A的右端),列舉過程i到j的長度是從小到大的,因此計算第i個字元到第j個字元時,在(i,j)位置的dp值是可知的,具體看程式碼,不難理解
#include<cstdio> #include<stack> #include<set> #include<vector> #include<queue> #include<algorithm> #include<cstring> #include<string> #include<map> #include<iostream> #include<cmath> using namespace std; #define inf 0x3f3f3f3f typedef long long ll; const int N=300; const double esp = 1e-9; const double PI=3.1415926; char ch[N]; int dp[N][N],pos[N][N]; void solve(int i,int j) { if(i>j) return; if(i==j) { if(ch[i]=='('||ch[j]==')') printf("()"); else printf("[]"); } else if(pos[i][j]==-1) { printf("%c",ch[i]); solve(i+1,j-1); //遞迴中間部分的過程 printf("%c",ch[j]); } else { solve(i,pos[i][j]); solve(pos[i][j]+1,j); } } int main() { while(gets(ch)!=NULL) //不能用scanf輸入,scanf不能輸入帶空格字串 { int len=strlen(ch); memset(dp,0,sizeof(dp)); for(int i=0; i<len; i++) { dp[i][i]=1; } for(int t=1; t<len; t++) { for(int i=0; i+t<len; i++) { int j=i+t; dp[i][j]=inf; if((ch[i]=='('&&ch[j]==')')||(ch[i]=='['&&ch[j]==']')) { dp[i][j]=dp[i+1][j-1]; pos[i][j]=-1; } for(int mid=i; mid<j; mid++) //計算是否有更優解 { int ans=dp[i][mid]+dp[mid+1][j]; if(dp[i][j]>ans) { pos[i][j]=mid; dp[i][j]=ans; } } } } solve(0,len-1); printf("\n"); } return 0; }