Brackets Sequence
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 25965 |
|
Accepted: 7323 |
|
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
Northeastern Europe 2001
//注意状态转移的过程 明白什么是状态转移的本质
#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 105
using namespace std;
char s[105];
int d[105][105],len;
bool match(char a, char b)
{
if((a=='('&&b==')')||(a=='['&&b==']'))
return true ;
return false ;
}
void dp()
{
for(int i=0; i<len; i++)
{
d[i][i]=1;
d[i+1][i]=0;
}
for(int i=len-1; i>=0; i--)
for(int j=i+1; j<len; j++)
{
d[i][j]=maxn;
if(match(s[i],s[j]))
d[i][j]=min(d[i][j],d[i+1][j-1]);
for(int k=i; k<j; k++)
d[i][j]=min(d[i][j],d[i][k]+d[k+1][j]);
}
}
void print(int i, int j)
{
if(i>j) return;
if(i==j)
{
if(s[i]=='('||s[i]==')')
cout<<"()";
else cout<<"[]";
return;
}
if(match(s[i],s[j])&&d[i][j]==d[i+1][j-1])
{
cout<<s[i];
print(i+1,j-1);
cout<<s[j];
return ;
}
for(int k=i; k<j; k++)
{
if(d[i][j]==d[i][k]+d[k+1][j])
{
print(i,k);
print(k+1,j);
return ;
}
}
}
int main()
{
while(gets(s))
{
len=strlen(s);
dp();
print(0,len-1);
cout<<endl;
}
return 0;
}