Partitioning by Palindromes—最小组成回文串(区间dp)

版权声明:若有转载,请标注原博客地址!谢谢 https://blog.csdn.net/DreamTrue1101/article/details/83820575

题目链接:Partitioning by Palindromes UVA - 11584 


题意:输入一个有小写字母组成的字符串,你的任务是将它划分成尽量少的回文串

思路:dp[i]代表到第i位的最小值,枚举它的前几位求出最小值,为了方便枚举整个长度我们 从str[1]开始输入

代码如下:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
#include<math.h>
#define inf 1e6
using namespace std;
typedef long long ll;
char arr[1010];
int dp[1010];
bool Find(int l,int r)  //   判断是否为回文串
{
    for(int i=l,j=r;i<j;i++,j--){
        if(arr[i]!=arr[j])
            return false;
    }
    return true;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%s",arr+1);
        memset(dp,0,sizeof(dp));
        int num=strlen(arr+1);
        for(int i=1;i<=num;i++){
            dp[i]=i;
            for(int j=1;j<=i;j++){
                if(Find(j,i))
                    dp[i]=min(dp[i],dp[j-1]+1);
            }
        }
        printf("%d\n",dp[num]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/DreamTrue1101/article/details/83820575
今日推荐