Light OJ 1044 Palindrome Partitioning (hash+DP)

题意:给出一个字符串,求其最少由多少个连续的回文子串构成。

解析:hash用来判一个子串是否是回文串,正反预处理保存各个位置上的hash值。

dp[i]:下标1~i对应的子串最少由多少个连续的回文子串构成。

dp[i] = min(dp[j-1]+1)  (j<=i,且j到i能形成一个回文串)

[code]:

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
typedef long long LL;
const LL MOD = 1e9+7;

char s[1005];
int n,dp[1005];
LL Hash[2][1005],Mul[1005];

void hash(){
    int i,j;
    Hash[0][0] = Hash[1][n+1] = 0;
    for(i = 1;i <= n;i++) Hash[0][i] = Hash[0][i-1]*MOD + s[i];
    for(i = n;i >= 1;i--) Hash[1][i] = Hash[1][i+1]*MOD + s[i];
}

bool check(int a,int b){
    int mid = (b-a+2)/2;
    return Hash[0][a+mid-1]-Hash[0][a-1]*Mul[mid]
        == Hash[1][b-mid+1]-Hash[1][b+1]*Mul[mid];
}

int main(){
    int i,j,cas,T;
    Mul[0] = 1;
    for(i = 1;i < 1005;i++) Mul[i] = MOD*Mul[i-1];
    scanf("%d",&cas);
    for(T = 1;T <= cas;T++){
        scanf("%s",s+1);
        n = strlen(s+1);
        memset(dp,63,(n+1)*sizeof(int));
        hash();
        dp[0] = 0;
        for(i = 1;i <= n;i++){
            for(j = i;j >= 1;j--){
                if(check(j,i)){
                    dp[i] = min(dp[i],dp[j-1]+1);
                }
            }
        }
        printf("Case %d: %d\n",T,dp[n]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值