poj 1141 Brackets Sequence

#include<iostream>
#include
<string>
#define max 9999
using namespace std;
char s[110];
int ans[110][110],pipei[110][110];

void output(int x,int y)
{
if(x>y) return ;
else if(x==y)
{
if(s[x]=='('||s[x]==')')
printf(
"()");
else
printf(
"[]");
}
else
{
if(pipei[x][y]==-1)
{
printf(
"%c",s[x]);
output(x
+1,y-1);
printf(
"%c",s[y]);
}
else
{
output(x,pipei[x][y]);
output(pipei[x][y]
+1,y);
}
}
}
int main()
{
while(gets(s))
{
int dis,k,i,j;
int len=strlen(s);
if(!len)
{
printf(
"\n"); continue;
}
memset(ans,
0,sizeof(ans));
for(i=0;i<len;i++)
ans[i][i]
=1; //ans[i][i]表示只有一个字符如 ] 则它只需添加1个字符匹配后变成 [ ] ,所以是1
for(dis=1;dis<len;dis++)
for(i=0;i<len-dis;i++)
{
j
=i+dis;
ans[i][j]
=max;
if((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']')) //当s[i]与s[j]匹配时,ans[i,j]=ans[i+1,j-1].此时pipei[i][j]标记为-1
ans[i][j]=ans[i+1][j-1],pipei[i][j]=-1;
for(k=i;k<j;k++) //在i->j找出使(ans[i,k]+ans[k+1,j])最小的K,ans[i,j]=ans[i,k]+ans[k+1,j].
{
if(ans[i][k]+ans[k+1][j]<ans[i][j])
ans[i][j]
=ans[i][k]+ans[k+1][j],pipei[i][j]=k;
}
}
output(
0,len-1);
printf(
"\n");
}
return 0;
}

  

posted on 2011-07-17 23:50  sysu_mjc  阅读(155)  评论(0编辑  收藏  举报

导航