70 pts dp 求调
查看原帖
70 pts dp 求调
448873
Pig_py楼主2023/10/3 14:50
#include<bits/stdc++.h>
using namespace std;
int dp[505][505],n;
char a[505];
const int inf=10000000;
bool check(int l,int r){
	for(int i=l+1;i<=r;i++){
		if(a[i]!=a[i-1]){
			return false;
		}
	}
	return true;
}
int Dfs1(int l,int r){
	if(dp[l][r])return dp[l][r];
	else if(l>r)return (dp[l][r]=0);
	else if(check(l,r)) return (dp[l][r]=1);
	dp[l][r]=inf;
	int now=inf,res=1;
	for(int i=l;i<=r;i++){
		if(a[i]==a[l]){
			if(now!=inf){
				res+=Dfs1(now,i-1);
				now=inf;
			}
		}
		else{
			now=min(now,i);
		}
	}
	if(now!=inf){
		res+=Dfs1(now,r);
	}
	dp[l][r]=min(dp[l][r],res);
	now=0,res=1;
	for(int i=r;i>=l;i--){
		if(a[i]==a[r]){
			if(now){
				res+=Dfs1(i+1,now);
				now=0;
			}
		}
		else{
			now=max(now,i);
		}
	}
	if(now){
		res+=Dfs1(l,now);
	}	
	dp[l][r]=min(dp[l][r],res);
	for(int l1=l;l1<=r;l1++){
		for(int r1=l1;r1<=r;r1++){
			if(l1==l&&r1==r)continue;
			//if(check(l1,r1)){
/*			if(l==3&&r==5){
				printf("l1:%d r1:%d res:%d\n",l1,r1,Dfs1(l,l1-1)+res+Dfs1(r1+1,r));
			}*/
			dp[l][r]=min(dp[l][r],Dfs1(l,l1-1)+Dfs1(l1,r1)+Dfs1(r1+1,r));	 
			//}
		}
	}
	//printf("l:%d r:%d dp[l][r]:%d\n",l,r,dp[l][r]);
	return dp[l][r];
}
int main(){
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	scanf("%s",a+1);
	n=strlen(a+1);
	printf("%d\n",Dfs1(1,n));
/*    for(int i=1;i<=n;i++){
    	for(int j=i;j<=n;j++){
    		printf("dp[%d][%d]=%d\n",i,j,dp[i][j]);
		}
	}	*/
}
/*
dp[l][r] 表示涂好 l~r 区间所需要的最小花费 

SYMFFBFUF
*/
2023/10/3 14:50
加载中...