D. Flood Fill(区间dp)

题目链接:http://codeforces.com/contest/1114/problem/D

题面:

 

 题意:给你一个颜色的数组,每次都将一个颜色区间改变为任意一个颜色,要求把他全部转化为一个颜色所需要的最小的操作步数

思路:dp[l][r][0/1]表示将l到r区间的颜色变为同一颜色的最小操作步数,0表示和最左边相同,1表示和最右边相同,然后就是类似dfs的记忆化搜索。

代码:

#include<bits/stdc++.h>
using namespace std;

const int maxn = 5007;
int dp[5007][5007][2],a[maxn],b[maxn];

int dpp(int l,int r,int p){
	if(dp[l][r][p] != -1)return dp[l][r][p];
	if(l == r)return 0;
	if(l > r)return 0;
	if(p == 0){
		int res = dpp(l+1,r,0) + (a[l] != a[l+1]);
		res = min(res,dpp(l+1,r,1) + (a[l] != a[r]));
		dp[l][r][p] = res;
		return res;
	}
	if(p == 1){
		int res = dpp(l,r-1,0) + (a[r] != a[l]);
		res = min(res,dpp(l,r-1,1) + (a[r] != a[r-1]));
		dp[l][r][p] = res;
		return res;
	}
}

int main(){
	int n;
	cin >> n;
	memset(dp,-1,sizeof(dp));
	for(int i = 0;i < n; i++){
		cin >> a[i];
	}
	int cnt = 0;
	b[cnt++] = a[0];
	for(int i = 1;i < n; i++){
		if(a[i] != a[i-1]){
			b[cnt++] = a[i];
		}
	}
	for(int i = 0;i < cnt; i++)a[i] = b[i];
	int ans;
	ans = min(dpp(0,cnt-1,0),dpp(0,cnt-1,1));
	cout<< ans << endl;
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值