poj 3974 Palindrome(最长回文子串,处理大数,Manacher算法)

来源:互联网 发布:新疆seo外包 编辑:程序博客网 时间:2024/05/17 05:11

1、http://poj.org/problem?id=3974

2、题目大意:

给定一串字符串,输出最长回文串的长度,此题难点在于字符串长度1000000,用二维dp会超时,在此用Manacher算法解决,见上一篇博客

Palindrome
Time Limit: 15000MS Memory Limit: 65536KTotal Submissions: 2225 Accepted: 801

Description

Andy the smart computer science student was attending an algorithms class when the professor asked the students a simple question, "Can you propose an efficient algorithm to find the length of the largest palindrome in a string?"

A string is said to be a palindrome if it reads the same both forwards and backwards, for example "madam" is a palindrome while "acm" is not.

The students recognized that this is a classical problem but couldn't come up with a solution better than iterating over all substrings and checking whether they are palindrome or not, obviously this algorithm is not efficient at all, after a while Andy raised his hand and said "Okay, I've a better algorithm" and before he starts to explain his idea he stopped for a moment and then said "Well, I've an even better algorithm!".

If you think you know Andy's final solution then prove it! Given a string of at most 1000000 characters find and print the length of the largest palindrome inside this string.

Input

Your program will be tested on at most 30 test cases, each test case is given as a string of at most 1000000 lowercase characters on a line by itself. The input is terminated by a line that starts with the string "END" (quotes for clarity).

Output

For each test case in the input print the test case number and the length of the largest palindrome.

Sample Input

abcbabcbabcbaabacacbaaaabEND

Sample Output

Case 1: 13Case 2: 6

 

3、代码:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define N 1000005char str[2*N+2];char st[N];int p[2*N+2];int main(){    int cas=0;    while(scanf("%s",st)!=EOF)    {        if(strcmp(st,"END")==0)        break;        cas++;        int nn=strlen(st);        int n=2*nn+2;        str[0]='$';//str首位置赋值$        for(int i=0;i<=nn;i++)        {            str[2*i+2]=st[i];            str[2*i+1]='#';        }//str从下标1开始        int ans=-999;        memset(p,0,sizeof(p));//p[i]数组记录以str[i]为中心的最长回文子串的长度,p[i]-1即为原来字符串的长度        int mx=0;//mx用来记录p[i]中到达的最右端的值        int id;//id用来记录p[i]延长至最右端的下标i        for(int i=1;i<n;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(mx<i+p[i])            {                mx=i+p[i];                id=i;            }            if(ans<p[i])            ans=p[i];        }        printf("Case %d: %d\n",cas,ans-1);//输出的ans-1,即是最长的回文串长度    }    return 0;}/*abcbabcbabcbaabacacbaaaabEND*/


 

原创粉丝点击