POJ 3974 Manacher模版题

点击打开链接

题意:求最长回文子串

思路:Manacher算法的强大这里不解释了,推荐一篇很好的Manacher详解点这里

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1000010;
char str[maxn],tmp[maxn<<1];
int len1[maxn<<1];
int init(char *st){
    int len=strlen(st);
    tmp[0]='@';
    for(int i=1;i<=2*len;i+=2){
        tmp[i]='#';
        tmp[i+1]=st[i/2];
    }
    tmp[2*len+1]='#';
    tmp[2*len+2]='$';
    tmp[2*len+3]=0;
    return 2*len+1;
}
int Manacher(char *st,int len){
    int p=0,ans=0,po=0;
    for(int i=1;i<=len;i++){
        if(p>i) len1[i]=min(p-i,len1[2*po-i]);
        else len1[i]=1;
        while(st[i-len1[i]]==st[i+len1[i]]) len1[i]++;
        if(len1[i]+i>p){
            p=len1[i]+i;
            po=i;
        }
        ans=max(ans,len1[i]);
    }
    return ans-1;
}
int main(){
    int t=1;
    while(scanf("%s",str)!=-1){
        if(strcmp(str,"END")==0) break;
        init(str);
        int len=init(str);
        int ans=Manacher(tmp,len);
        printf("Case %d: %d\n",t++,ans);
    }
    return 0;
}

你可能感兴趣的:(数据结构,ACM,poj,马拉车)