51NOD 1154 回文串划分

题目链接https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1154

题意:略。

思路:先用Manacher对于字符串预处理,然后进行动态规划。设dp[i]为以i结尾的最少划分回文子串数量,然后枚举[0,i-1],看下当前枚举点和i的中心的回文半径长度加中心点是否超过i,如果超过则dp[i]=min(dp[i],dp[j]+1),扫一遍即可求出答案,最后答案即为dp[len]

#pragma comment(linker, "/STACK:102400000,102400000")
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define lson root<<1,l,mid
#define rson root<<1|1,mid+1,r
#define Key_Value ch[ch[root][1]][0]
#define DBN1(a)           cerr<<#a<<"="<<(a)<<"\n"
#define DBN2(a,b)         cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<"\n"
#define DBN3(a,b,c)       cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<"\n"
#define DBN4(a,b,c,d)     cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<"\n"
#define DBN5(a,b,c,d,e)   cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<"\n"
#define DBN6(a,b,c,d,e,f) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<", "<<#f<<"="<<(f)<<"\n"
#define clr(a,x) memset(a,x,sizeof(a))
using namespace std;
typedef long long ll;
const int maxn=5000+5;
const int INF=0x3f3f3f3f;
const int P=1000000007;
const double PI=acos(-1.0);
template<typename T>
inline T read(T&x){
    x=0;int _f=0;char ch=getchar();
    while(ch<'0'||ch>'9')_f|=(ch=='-'),ch=getchar();
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x=_f?-x:x;
}
template <class T1, class T2>inline void gmax(T1 &a, T2 b) { if (b>a)a = b; }
template <class T1, class T2>inline void gmin(T1 &a, T2 b) { if (b<a)a = b; }
char Ma[maxn*2];
int Mp[maxn*2],dp[maxn];
char s[maxn];
int main(){
    scanf("%s",s);
    int l=0,len=strlen(s);
    Ma[l++]='$';
    Ma[l++]='#';
    for (int i=0;i<len;i++){
        Ma[l++]=s[i];
        Ma[l++]='#';
    }
    Ma[l]=0;
    int mx=0,id=0;
    for (int i=0;i<l;i++){
        Mp[i]=mx>i?min(Mp[2*id-i],mx-i):1;
        while (Ma[i+Mp[i]]==Ma[i-Mp[i]]) Mp[i]++;
        if (i+Mp[i]>mx){
            mx=i+Mp[i];
            id=i;
        }
    }
    for (int i=1;i<=len;i++){
        dp[i]=i;
        for (int j=0;j<i;j++){
            int posa=i*2,posb=(j+1)*2;
            int mid=(posa+posb)>>1;
            if (Mp[mid]>=posa-mid+1){
                dp[i]=min(dp[i],dp[j]+1);
            }
        }
    }
    printf("%d\n",dp[len]);
    return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注