POJ 1141 Brackets Sequence

来源:互联网 发布:淘宝韩版男装店铺推荐 编辑:程序博客网 时间:2024/04/29 11:26
经典的DP,黑书上有,不过要递归求解,以前很少构造最优解,在看了大牛的代码后,也发现黑书的代码也是有待改进的。
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11216 Accepted: 2995 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<stdio.h>
#include<string.h>
char str[110];
int d[110][110],path[110][110];
void ou(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]);
        ou(i+1,j-1);
        printf("%c",str[j]);
    }
    else
 {
        ou(i,path[i][j]);
        ou(path[i][j]+1,j);
    }
}
int main()
{
 freopen("in.txt","r",stdin);
 freopen("out.txt","w",stdout);
 int n,k,i,j,p;
 while(gets(str))//再次明晰了怎么使用GETS
 {
  memset(path,0,sizeof(path));
  n=strlen(str);
  if(n==0) //极端情况的考虑
  {
   printf("/n");
   continue;
     }
  for(i=1;i<=n;i++)
  {
     d[i][i]=1;
     d[i][i-1]=0;
  }
  for(k=1;k<=n-1;k++)
    for(i=0;i<n-k;i++)
      {
    j=i+k;
    d[i][j]=1<<25;
    if((str[i]=='['&&str[j]==']')||(str[i]=='('&&str[j]==')'))
        if(d[i][j]>d[i+1][j-1])//这里可能出现D[I][I-1]
          d[i][j]=d[i+1][j-1],path[i][j]=-1;
    /*(str[i-1]=='('||str[i-1]=='[')
           if(d[i][j]<d[i+1][j]+1);//这里都可能出现D[I][I]
       d[i][j]=d[i+1][j]+1;
    if(str[j-1]==')'||str[j-1]==']')
        if(d[i][j]<d[i][j-1]+1)
           d[i][j]=d[i][j-1]+1;*///这两种可能其实已经包括在下面的循环中
    for(p=i;p<j;p++)
        if(d[i][j]>d[i][p]+d[p+1][j])
           d[i][j]=d[i][p]+d[p+1][j],path[i][j]=p;
   }
  ou(0,n-1);
  printf("/n");                       
 }
 return 0;
}
原创粉丝点击