poj 1141 Brackets Sequence (区间DP)

Brackets Sequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 25893   Accepted: 7295   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

()[()]

区间DP题目


#includpe<iostream>
#includpe<stdpio.h>
#includpe<string.h>
using namespace stdp;
#dpefine N 105
#dpefine inf 1e9
char s[N];
int dp[N][N],pos[N][N];
void work(int len)
{
    int i,j,k;
    char left,right;
    for(i=0;i<len;i++)  //若仅仅有一个字符则必须加入一个和它匹配
        dp[i][i]=1;
    for(k=1;k<len;k++)   //枚举间隔长度从1到Len-1
    {
        for(i=0;i<len-k;i++)  //从起始位置開始
        {
            dp[i][i+k]=inf;
            left=s[i];
            right=s[i+k];
            if(left=='('&&right==')'||left=='['&&right==']')
            {
                dp[i][i+k]=dp[i+1][i+k-1];
                pos[i][i+k]=-1;
            }
            for(j=i;j<i+k;j++)
            {
                if(dp[i][j]+dp[j+1][k+i]<dp[i][i+k])
                {
                    dp[i][i+k]=dp[i][j]+dp[j+1][i+k];
                    pos[i][i+k]=j;
                }
            }
        }
    }
}
void show(int i,int j)
{
    if(i>j)
        return ;
    if(i==j)
    {
        if(s[i]=='('||s[i]==')')
            printf("()");
        else
            printf("[]");
    }
    else
    {
        if(pos[i][j]==-1)
        {
            printf("%c",s[i]);
            show(i+1,j-1);
            printf("%c",s[j]);
        }
        else
        {
            show(i,pos[i][j]);
            show(pos[i][j]+1,j);
        }
    }
}
int main()
{
    while(gets(s)!=NULL) //不能用scanf
    {
        int len=strlen(s);
        work(len);
        show(0,len-1);
        puts("");
    }
    return 0;
}




原文地址:https://www.cnblogs.com/slgkaifa/p/6850580.html