码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3974 Palindrome

时间:2016-05-04 22:40:59      阅读:370      评论:0      收藏:0      [点我收藏+]

标签:

D - Palindrome
Time Limit:15000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

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

abcbabcbabcba
abacacbaaaab
END

Sample Output

Case 1: 13
Case 2: 6

 

 
 1 //经典manachar
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<iostream>
 5 #include<algorithm>
 6 using namespace std;
 7 #define MAXN  2010000
 8 int p[MAXN];
 9 char s1[MAXN],s2[MAXN];
10 int manachar(int m){
11     int i,ans=0,mx=-1,id=-1;
12     for(i=1;i<=m;i++){
13       if(id+mx>=i) p[i]=min(p[id*2-i],id+mx-i);
14     while(i-p[i]-1>=0&&i+p[i]+1<=m&&s2[i-p[i]-1]==s2[i+p[i]+1]) p[i]++; 
15       if(i+p[i]>id+mx)
16          mx=p[i],id=i;
17        ans=max(ans,p[i]);
18      }
19      return ans;
20 } 
21 void deal(int m){
22      for(int i=0;i<m;i++)
23         s2[i*2+1]=s1[i],s2[i*2+2]=#;
24      s2[0]=#;
25      s2[m*2+1]=\0;
26      memset(p,0,sizeof(p));
27 }
28 int main()
29 {
30        int cnt=0;
31        while(scanf("%s",s1)){
32            if(strcmp(s1,"END")==0)break;
33            int m=strlen(s1);
34         deal(m);
35            printf("Case %d: %d\n",++cnt,manachar(m*2+1));
36        }
37 }

 

POJ 3974 Palindrome

标签:

原文地址:http://www.cnblogs.com/shenben/p/5459916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!