Brackets Sequence
Time limit:1000 ms |
|
Memory limit:65536 K |
|
|
|
|
Special Judge |
Description
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
()[()]
Source
The path of the DP record in the northeastern Europe 2001 range, which is combined with the matching of the brackets in the previous two questions + modifying the echo string .. Note empty rows
1 #include<set> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 #include<iostream> 6 #include<algorithm> 7 using namespace std; 8 const int N = 110; 9 #define For(i,n) for(int i=1;i<=n;i++)10 #define Rep(i,l,r) for(int i=l;i<=r;i++)11 #define Down(i,r,l) for(int i=r;i>=l;i--)12 13 struct State{14 int v,op;15 }dp[N][N];16 17 char st[N];18 int n;19 20 bool match(int x,int y){21 if(st[x]==‘(‘) return (st[y]==‘)‘);22 if(st[x]==‘[‘) return (st[y]==‘]‘);23 return false;24 }25 void DP(){26 n=strlen(st+1);27 For(i,n)28 For(j,n)29 if(j<i) dp[i][j].v=0;30 else dp[i][j].v=214748364;31 For(i,n) dp[i][i].v=1;32 Down(i,n-1,1)33 Rep(j,i,n){34 if(match(i,j))35 if(dp[i][j].v>dp[i+1][j-1].v){36 dp[i][j].v=dp[i+1][j-1].v;37 dp[i][j].op=0;38 }39 Rep(k,i,j-1)40 if(dp[i][k].v+dp[k+1][j].v<dp[i][j].v){41 dp[i][j].v=dp[i][k].v+dp[k+1][j].v;42 dp[i][j].op=k;43 }44 }45 }46 47 void Print(int l,int r){48 if(l>r) return;49 if(l==r){50 if(st[l]==‘(‘||st[l]==‘)‘) printf("()");51 if(st[l]==‘]‘||st[l]==‘[‘) printf("[]");52 return;53 }54 if(dp[l][r].op){55 Print(l,dp[l][r].op);56 Print(dp[l][r].op+1,r);57 }58 else{59 printf("%c",st[l]);60 Print(l+1,r-1);61 printf("%c",st[r]);62 }63 }64 65 int main(){66 while(gets(st+1)){67 if(strlen(st+1)){68 DP();69 Print(1,n);70 }71 puts("");72 }73 return 0;74 }
Poj 1141 brackets Sequence