Brackets Sequence

来源:互联网 发布:法院速录员听打软件 编辑:程序博客网 时间:2024/05/21 14:58
Brackets Sequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 31650 Accepted: 9120 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

()[()]

//求添加最小的数目,使得括号匹配,并输出已匹配的括号#include<stdio.h>#include<string.h>#define INF 0x3ffffffconst int N = 105;char str[N];int dp[N][N], flag[N][N];bool judge(char a, char b){    if(a == '(' && b == ')') return true;    if(a == '[' && b == ']') return true;    return false;}void print(int i, int j){    if(i > j) return ;    if(i == j)    {        if(str[i] == '[' || str[i] == ']') printf("[]");        else printf("()");    }    else if(flag[i][j] == -1)    {        printf("%c",str[i]);        print(i+1, j-1);        printf("%c",str[j]);    }    else    {        print(i, flag[i][j]);        print(flag[i][j] + 1, j);    }}int main(){    while(gets(str) != NULL)    {        int len = strlen(str);        memset(dp, 0, sizeof(dp));        for(int i = 0; i < len; i++)            dp[i][i] = 1;        for(int i = 1; i < len; i++)        {            for(int l = 0; l + i < len; l++)            {                int r = l + i;                dp[l][r] = INF;                if(judge(str[l], str[r]))                {                    if(dp[l][r] > dp[l+1][r-1])                        dp[l][r] = dp[l+1][r-1], flag[l][r] = -1; //flag[l][r]=-1表示str[l]与str[j]匹配时最优                }                for(int k = l; k < r; k++)                    if(dp[l][r] > dp[l][k] + dp[k+1][r])                        dp[l][r] = dp[l][k] + dp[k+1][r], flag[l][r] = k; //flag[l][r]=k表示以k为分割点的两端的匹配之和最优            }        }        //printf("%d\n",dp[0][len-1]);        print(0, len-1);        printf("\n");    }    return 0;}


0 0