poj1141根据不同规模构造最优子问题求解DP

61 篇文章 0 订阅
19 篇文章 0 订阅
//按照子问题的规模来枚举解决最优子问题,类似问题有算导上的最优矩阵乘法链
//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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值