//按照子问题的规模来枚举解决最优子问题,类似问题有算导上的最优矩阵乘法链
//600K 32MS
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX_N 2500
#define For(i,a,b) for(int i=a;i<=b;++i)
#define INF 0x3f3f3f3f
static int dp[MAX_N][MAX_N];
static char str[105];
//递归寻找最优解
static void printAns(int i,int j)
{
if (i==j){
char ch = str[i];
if (ch=='('||ch==')')
printf("()");
else if (ch=='['||ch==']')
printf("[]");
return;
}
if (((str[i]=='('&&str[j]==')')||(str[i]=='['&&str[j]==']'))
&&dp[i][j]==dp[i+1][j-1]){
printf("%c",str[i]);
printAns(i+1,j-1);
printf("%c",str[j]);
}
else if ((str[i]=='('||str[i]=='[')&&dp[i][j]==dp[i+1][j]+1){
printf("%c",str[i]);
printAns(i+1,j);
if (str[i]=='(')
printf(")");
else
printf("]");
}
else if ((str[j]==')'||str[j]==']')&&dp[i][j]==dp[i][j-1]+1)
{
if(str[j]==')')
printf("(");
else
printf("[");
printAns(i,j-1);
printf("%c",str[j]);
}
//没有补充括号的情况
else
{
For(k,i,j-1)
{
if (dp[i][j]==dp[i][k]+dp[k+1][j])
{
printAns(i,k);
printAns(k+1,j);
break;
}
}
}
}
static void DP(int n)
{
For(i,0,n-1)For(j,0,n-1){if(i>j)dp[i][j]=0;if (i==j)dp[i][i]=1;}
For(l,1,n)//枚举所有规模的子问题
For(i,0,n-l)
{
int j = i+l-1;
dp[i][j] = INF;
if ((str[i]=='('&&str[j]==')')||(str[i]=='['&&str[j]==']'))
dp[i][j] = min(dp[i][j],dp[i+1][j-1]);
//对开始和结尾的括号添加
if (str[i]=='('||str[i]=='[')
dp[i][j] = min(dp[i][j],dp[i+1][j]+1);
if (str[j]==')'||str[j]==']')
dp[i][j] = min(dp[i][j],dp[i][j-1]+1);
//否则不对开始和结尾处的括号进行添加
For(k,i,j-1)
dp[i][j] = min(dp[i][j],dp[i][k]+dp[k+1][j]);
}
}
int main()
{
while(gets(str))
{
int l = strlen(str);
if (!l)
printf("\n");
else{
DP(l);
printAns(0,l-1);
printf("\n");
}
}
return 0;
}
poj1141根据不同规模构造最优子问题求解DP
最新推荐文章于 2020-12-20 20:51:49 发布