POJ 1141 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

()[()]

Source


    设dp[i,j]为从位置i到位置j需要加入字符的最小次数,有dp[i,j]=min(dp[i,k]+dp[k+1,j]),其中i<=k<j。特别的当s[i]='[' s[j]=']'或者s[i]='(' s[j]=')'时,dp[i,j]=dp[i+1,j-1]。初始条件为dp[i,i]=1,其中0<=i<len。
#include <iostream>
using namespace std;

const int MAXN = 110;
char str[MAXN];
int dp[MAXN][MAXN],path[MAXN][MAXN];

void output(int i,int j){
    
if(i>j) return;
    
if(i==j){
        
if(str[i]=='[' || str[i]==']') printf("[]");
        
else printf("()");
    }

    
else if(path[i][j]==-1){
        printf(
"%c",str[i]);
        output(i
+1,j-1);
        printf(
"%c",str[j]);
    }

    
else{
        output(i,path[i][j]);
        output(path[i][j]
+1,j);
    }

}

int main(){
    
int i,j,k,r,n;
    
while(gets(str)){
        n
=strlen(str);
        
if(n==0){
            printf(
"\n");
            
continue;
        }

        memset(dp,
0,sizeof(dp));
        
for(i=0;i<n;i++) dp[i][i]=1;
        
for(r=1;r<n;r++)
            
for(i=0;i<n-r;i++){
                j
=i+r;
                dp[i][j]
=INT_MAX;
                
if((str[i]=='(' && str[j]==')')||(str[i]=='[' && str[j]==']'))
                    
if(dp[i][j]>dp[i+1][j-1])
                        dp[i][j]
=dp[i+1][j-1],path[i][j]=-1;
                
for(k=i;k<j;k++)
                    
if(dp[i][j]>dp[i][k]+dp[k+1][j])
                        dp[i][j]
=dp[i][k]+dp[k+1][j],path[i][j]=k;
            }

        output(
0,n-1);
        printf(
"\n");
    }

    
return 0;
}

posted on 2009-06-29 11:31 极限定律 阅读(2684) 评论(0)  编辑 收藏 引用 所属分类: ACM/ICPC


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


<2009年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(10)

随笔分类

随笔档案

友情链接

搜索

最新评论

阅读排行榜

评论排行榜