POJ 题目1141 Brackets Sequence(区间DP记录路径)
Brackets Sequence
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 27793 | Accepted: 7885 | 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.
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
ac代码
#include<stdio.h> #include<string.h> char str[330]; int a[330][330],b[330],dp[330][330]; void print(int l,int r) { if(l>=r) return; if(a[l][r]==-1) { print(l+1,r); } if(a[l][r]>0) { b[l]=1; b[a[l][r]]=1; print(l+1,a[l][r]-1); print(a[l][r],r); } } int main() { while(gets(str+1)) { int i,j,k; memset(dp,0,sizeof(dp)); memset(a,-1,sizeof(a)); memset(b,0,sizeof(b)); int len=strlen(str+1); for(i=1;i<=len;i++) { dp[i][i]=1; } for(i=len-1;i>=1;i--) { for(j=i+1;j<=len;j++) { dp[i][j]=dp[i+1][j]+1; //a[i][j]=-1; for(k=i+1;k<=j;k++) { if((str[i]=='('&&str[k]==')')||(str[i]=='['&&str[k]==']')) { if(dp[i][j]>dp[i+1][k-1]+dp[k][j]-1) { dp[i][j]=dp[i+1][k-1]+dp[k][j]-1; a[i][j]=k; // b[i]=1; // b[a[i][j]]=1; } } } } } print(1,len); for(i=1;i<=len;i++) { if(b[i]==1) { printf("%c",str[i]); } else if(str[i]=='('||str[i]==')') printf("()"); else printf("[]"); } printf("\n"); } }