nyoj 15

令res[i][j]表示从str[i]到str[j]需要添加字符的个数;

如果str[k]与str[i]匹配,  res[i][j]=min(res[i][j], res[i+1][k-1]+res[k+1][j]);

如果str[k]与str[j]匹配,  res[i][j]=min(res[i][j],res[i][k-1]+res[k+1][j-1] );

如果str[k]与str[i]和str[j]都不匹配,res[i][j]=min(res[i][j],res[i][k-1]+res[k+1][j]+1 );

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAX 1234567890
char str[110];
int res[110][110];
int min(int a,int b)
{
return a < b ? a : b;
}
int check(int i,int j)
{
if(str[i]=='[' && str[j]==']') return 1;
if(str[i]=='(' && str[j]==')') return 1;
return 0;
}
int work(int n)
{
int i,j,k;
for(i=1;i<=n;i++) res[i][i]=1;
for(i=1;i<=n;i++)
{
for(j=i-1;j>0;j--)
{
res[j][i]=MAX;
for(k=j;k<=i;k++)
{
if(check(j,k)) res[j][i]=min(res[j][i],res[j+1][k-1]+res[k+1][i]);
if(check(k,i)) res[j][i]=min(res[j][i],res[j][k-1]+res[k+1][i-1]);
if(!check(k,i) && !check(j,k)) res[j][i]=min(res[j][i],res[j][k-1]+res[k+1][i]+1);
}
}
}
return res[1][n];
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
scanf("%s",str+1);
memset(res,0,sizeof(res));
printf("%d\n",work(strlen(str+1)));
}
return 0;

}



你可能感兴趣的:(OJ)