POJ Brackets Sequence

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

()[()]
递推方式
View Code
#include<stdio.h>
#include<string.h>
int dp[103][103];
int pa[103][103];
char s[103];
#define inf 999
void print(int l,int r)
{
if(l>r) return;
else if(l==r)
{
if(s[l]=='('||s[l]==')')
printf("()");
else if(s[l]=='['||s[l]==']')
printf("[]");
}
else if(pa[l][r]==-1)
{
printf("%c",s[l]);
print(l+1,r-1);
printf("%c",s[r]);
}
else
{
print(l,pa[l][r]);
print(pa[l][r]+1,r);
}
}
int main()
{
int p,len,i,j,k;
while(gets(s+1))
{
len=strlen(s+1);
memset(dp,0,sizeof(dp));
memset(pa,0,sizeof(pa));
for(i=1;i<=len;i++)
dp[i][i]=1;
for(p=1;p<len;p++)
{
for(i=1;i<=len-p;i++)
{
j=i+p;
dp[i][j]=inf;
if((s[i]=='['&&s[j]==']')||(s[i]=='('&&s[j]==')'))
{
dp[i][j]=dp[i+1][j-1];
pa[i][j]=-1;
}
for(k=i;k<j;k++)
{
if(dp[i][k]+dp[k+1][j]<dp[i][j])
{
dp[i][j]=dp[i][k]+dp[k+1][j];
pa[i][j]=k;
}
}
}
}
print(1,len);
printf("\n");
}
return 0;
}

posted @ 2012-04-01 21:10  'wind  阅读(299)  评论(0编辑  收藏  举报