POJ1141 Brackets Sequence

时间:2021-07-28 05:52:04

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

解题报告:

  DP题,乍一看我居然不会做,也是醉了。开始想用贪心水过,发现会gi烂。

  详细博客:http://blog.csdn.net/lijiecsu/article/details/7589877

  不详细说了,见代码:

 #include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;
const int MAXN = ;
char ch[MAXN];
int l;
int f[MAXN][MAXN],c[MAXN][MAXN]; inline void output(int l,int r){
if(l>r) return ;
if(l==r) {
if(ch[l]=='(' || ch[l]==')') printf("()");
else printf("[]");
}
else{
if(c[l][r]>=) {
output(l,c[l][r]);
output(c[l][r]+,r);
}
else{
if(ch[l]=='(') {
printf("(");
output(l+,r-);
printf(")");
}
else{
printf("[");
output(l+,r-);
printf("]");
}
}
}
} inline void solve(){
scanf("%s",ch);
int len=strlen(ch);
for(int i=;i<len;i++) f[i][i]=;
for(int i=;i<len;i++) for(int j=;j<len;j++) c[i][j]=-;
for(int l=;l<=len-;l++)
for(int i=;i+l<=len-;i++){
int j=i+l;
int minl=f[i][i]+f[i+][j];
c[i][j]=i;
for(int k=i+;k<j;k++){
if(minl>f[i][k]+f[k+][j]) {
minl=f[i][k]+f[k+][j];
c[i][j]=k;
}
}
f[i][j]=minl; if(( ch[i]=='(' && ch[j]==')' ) || ( ch[i]=='[' && ch[j]==']' )) {
if(f[i][j]>f[i+][j-]) {
f[i][j]=f[i+][j-];
c[i][j]=-;
}
}
} output(,len-);
printf("\n");
} int main()
{
solve();
return ;
}