Educational Codeforces Round 61 F 思维 + 区间dp

https://codeforces.com/contest/1132/problem/F
思维 + 区间dp

题意

给一个长度为n的字符串(<=500),每次选择消去字符,连续相同的字符可以同时消去,问最少需要消去多少次

题解

  • 定义dp[l][r]为区间[l,r]剩下一个字符所需要的最小次数
  • dp[l][r]=min(dp[l][i]+dp[i+1][r]+x)
  • x为消去剩下两个字符所需要的次数,假如两个字符相同需要x=-1

代码

#include<bits/stdc++.h>
#define ll long long 
using namespace std;
ll n,f[505][505];
char s[505];
ll dfs(int l,int r){
	if(l>r)return 0;
	if(l==r)return 1;
	ll &ans=f[l][r];
	if(ans!=-1)return ans;
	ans=1e17;
	for(int i=l;i<r;i++){
		ll tp=dfs(l,i)+dfs(i+1,r);
		if(s[l]==s[i+1]||s[i]==s[i+1]||s[i]==s[r]||s[l]==s[r])
			ans=min(ans,tp-1);
		else ans=min(ans,tp);
	}
	return ans;
}


int main(){
	cin>>n;
	scanf("%s",s+1);
	memset(f,-1,sizeof(f));
	cout<<dfs(1,n);
}
原文地址:https://www.cnblogs.com/VIrtu0s0/p/10488094.html