poj3974(manacher)

 

传送门:Palindrome

题意:给定一个字符串,求最长回文子串。

分析:manach裸题,核心理解mx>i?p[i]=min(p[2*id-i],mx-i):1.

#pragma comment(linker,"/STACK:1024000000,1024000000")

#include <cstdio>

#include <cstring>

#include <string>

#include <cmath>

#include <limits.h>

#include <iostream>

#include <algorithm>

#include <queue>

#include <cstdlib>

#include <stack>

#include <vector>

#include <set>

#include <map>

#define LL long long

#define mod 1000000007

#define inf 0x3f3f3f3f

#define eps 1e-6

#define N 1000010

#define lson l,m,rt<<1

#define rson m+1,r,rt<<1|1

#define PII pair<int,int>

using namespace std;

inline LL read()

{

    char ch=getchar();LL x=0,f=1;

    while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();}

    while(ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=getchar();}

    return x*f;

}

int p[N<<1],ans,len,num,mx,id;

char s[N],str[N<<1];

void build()

{

    len=strlen(s);num=0;

    str[num++]='@';str[num++]='#';

    for(int i=0;i<len;i++)

    {

        str[num++]=s[i];

        str[num++]='#';

    }

    str[num]=0;

}

void manacher()

{

    ans=0;mx=0;

    memset(p,0,sizeof(p));

    for(int i=1;i<num;i++)

    {

        if(mx>i)p[i]=min(p[2*id-i],mx-i);

        else p[i]=1;

        while(str[i-p[i]]==str[i+p[i]])p[i]++;

        if(p[i]+i>mx)mx=p[i]+i,id=i;

        if(ans<p[i]-1)ans=p[i]-1;

    }

}

int main()

{

    int cas=1;

    while(scanf("%s",s)>0)

    {

        if(strcmp(s,"END")==0)break;

        build();

        manacher();

        printf("Case %d: %d\n",cas++,ans);

    }

}
View Code

 

你可能感兴趣的:(poj)