#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#define debu
using namespace std;
const int INF=1e7;
const int maxn=200;
char st[maxn];
int d[maxn][maxn];
int check(char a,char b)
{
if(a=='('&&b==')') return 1;
if(a=='['&&b==']') return 1;
return 0;
}
void output(int i,int j)
{
if(i>j) return ;
if(i==j)
{
if(st[i]=='('||st[i]==')') printf("()");
else printf("[]");
return ;
}
int ans=d[i][j];
if(check(st[i],st[j])&&ans==d[i+1][j-1])
{
printf("%c",st[i]);
output(i+1,j-1);
printf("%c",st[j]);
return ;
}
for(int k=i; k<j; k++)
{
if(ans==d[i][k]+d[k+1][j])
{
output(i,k);
output(k+1,j);
return ;
}
}
}
void readline(char* st)
{
fgets(st, maxn, stdin);
}
int main()
{
#ifdef debug
freopen("in.in","r",stdin);
#endif // debug
int t;
readline(st);
sscanf(st, "%d", &t);
readline(st);
while(t--)
{
readline(st);
int l=strlen(st)-1;
for(int i=0;i<l;i++)
for(int j=0;j<l;j++)
d[i][j]=INF;
for(int i=0; i<l; i++)
{
d[i+1][i]=0;
d[i][i]=1;
}
for(int i=l-1; i>=0; i--)
for(int j=i+1; j<l; j++)
{
if(check(st[i],st[j])) d[i][j]=min(d[i][j],d[i+1][j-1]);
for(int k=i; k<j; k++)
d[i][j]=min(d[i][j],d[i][k]+d[k+1][j]);
}
output(0,l-1);
printf("\n");
if(t) printf("\n");
readline(st);
}
return 0;
}
UVA 1626(p278)----Brackets Sequence
最新推荐文章于 2020-06-01 12:04:59 发布