uva 11584 - Partitioning by Palindromes(简单dp)

https://vjudge.net/problem/UVA-11584

题目大意:

给一个字符串, 要求把它分割成若干个子串,使得每个子串都是回文串。问最少可以分割成多少个。

简单dp,P276.

#include<cstdio>
#include<algorithm>
#include<ctime>
#include<iostream>
#include<cmath>
#include<string.h>
using namespace std;
#define N 1000
char s[N];
// 检查是否为回文串
    bool isPalindrome(int l,int r)
	{
        
        while(l < r){
            if(s[l] != s[r])
                return false;
            ++l;
            --r;
        }
        return true;
    }

int main() {
	bool isPalindrome(int l,int r);
	int t,n,imin;
	int dp[N];
	scanf("%d",&t);
	while(t--)
	{
		scanf("%s",s);
		n=strlen(s);
		if(n<=1) 
		{
		   cout<<n<<endl;
		   continue;	
		} 
	    dp[0]=0;
		dp[1]=1;	   
		for(int i=2;i<=n;i++)
		{
			dp[i]=dp[i-1]+1;
			for(int j=0;j<i;j++)
			if(isPalindrome(j,i-1))
			{
				dp[i]=min(dp[j]+1,dp[i]);
			}
		}
		cout<<dp[n]<<endl; 
	} 
}

需要说明的问题:

1. 本题目和https://blog.csdn.net/qiang_____0712/article/details/84679892相同,但是需要输出所以的,得用回溯法。

本题目需要输出最小次数,使用dp。

2.该题目的复杂度为n^3,也有复杂度为n^2,的,参见

https://blog.csdn.net/luyuncheng/article/details/8247553

猜你喜欢

转载自blog.csdn.net/qiang_____0712/article/details/84954821