Brackets Sequence

来源:互联网 发布:macbook 软件下载 编辑:程序博客网 时间:2024/04/30 14:21
Brackets Sequence
Time Limit: 1000MS
Memory Limit: 65536KTotal Submissions: 16815
Accepted: 4568
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




//这道DP可以把字符串的长度看成是一个状态,长字符串是由子字符串的最优解得到,当字符串长度为1时均赋值为1,则当字符str[i]与str[j]匹配时,这时dp[i][j]=min(dp[i],dp[i+1][j-1])。对于不能品配的字符串dp[i][j]赋值为max;接着对长字符串进行DP一遍即可。
//如何记录输出的情况呢?这里采用的递归的思想,对之前记录的path值进行讨论,如果path[i][j]等于-1时,即匹配成功,这时输出前面的字符,接着继续递归;如果path[i][j]!=-1;这时则分别递归i到k,和k+1,j。
#include <stdio.h>
#include <string.h>
char str[105];
int path[105][105];
void print(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]);
      print(i+1,j-1);
      printf("%c",str[j]);
    }
  else
    {
      print(i,path[i][j]);
      print(path[i][j]+1,j);
    }
}


int main()
{
  int dp[105][105];
  int i,j,r,k;
  while(gets(str))
    {
      int len=strlen(str);
/*
*注意此处
*/
      if(len==0)
    {
      printf("\n");
      continue;
    }

      memset(dp,0,sizeof(dp));
//初始化
      for(i=0;i<len;i++)
    dp[i][i]=1;

      for(r=1;r<len;r++)
    {
      for(i=0;i<len-r;i++)
        {
          int j=r+i;
          dp[i][j]=99999999;

          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;
          }

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

原创粉丝点击