【贪心与动态规划】训练题E - Partitioning by Palindromes

题意

(越来越顺手了 开心子)

给定一个字符串,按照回文串分割,要求计算出最少的份数

思路

首先划分的要求是回文串,可以用二维数组ok[i][j]来表示,从i到j是否为回文串。

dp【i】数组则表示,从0到i最少可分割成多少份。

如果从s[j+1]到s[i]都为回文串,那么dp[i]=dp[j]+1。

代码

#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#define Endl "\n"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 1e3+5;
const int INF = 0x3f3f3f;
const int mod = 1e9 + 7;
const double pi = acos(-1); 
inline ll read(){
	ll x = 0, f = 1; char ch; ch = getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}
int n,ans;
int ok[maxn][maxn];
int dp[maxn];
char s[maxn];
void is_huiwen(){
	memset(ok,0,sizeof(ok));
	for(int i=0;i<n;i++)
	{
		ok[i][i]=1;
		for(int j=1;;j++)
		{
			int p=i-j;
			int q=i+j;
			if(p<0||q>=n) break;
			if(s[p]==s[q])
			{
				ok[p][q]=1;
			}
			else break;
		}
	}
	
	for(int i=0;i<n-1;i++)
	{
		if(s[i]!=s[i+1]) continue;
		ok[i][i+1]=1;
		for(int j=1;;j++)
		{
			int p=i-j;
			int q=i+1+j;
			if(p<0||q>=n) break;
			if(s[p]==s[q])
				ok[p][q]=1;
			else break;
		}
	}
	return ;
}
void solve() {
	scanf("%s",s);
	n=strlen(s);
	is_huiwen();
	dp[0]=1;
	for(int i=0;i<n;i++)
	{
		if(ok[0][i])
		{
			dp[i]=1;
			continue;
		}
		
		 ans=maxn;
		
		for(int j=0;j<i;j++)
		{
			if(ok[j+1][i])	ans=min(ans,dp[j]+1);
		}
		dp[i]=ans;
	}
	cout<<dp[n-1]<<Endl;
	return ; 
} 

int main() {
	for(int T = read(); T; T--)
		solve();
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值