Palindrome
Time Limit: 15000MS Memory Limit: 65536K
Total Submissions: 11961 Accepted: 4486
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
Source
题目大意:输入几串字符串,输出最长回文数
输入:碰到END就停止。
思路:Manacher马拉车模版
https://www.cnblogs.com/z360/p/6375514.html
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 10000000
char a[N];
char aa[N<<1];
int len[N<<1];//位运算,相当与二进制下向左挪一位并补0,也就是*2
using namespace std;
int INIT(char *st)
{
int len=strlen(a);
aa[0]='@';//这里是开头的,不能和结尾一样,这是同来判断越界的
for(int i=1;i<=2*len;i+=2)
{
aa[i]='#';
aa[i+1]=a[i/2];
}
aa[2*len+1]='#';
aa[2*len+2]='$';
aa[2*len+3]=0;
return 2*len+1;//返回长度即可
}
int MANACHER(char *st,int lena)
{
int mar=0;
int ans=0;
int po=0;
for(int i=1;i<=lena;i++)
{
if(mar>i)
len[i]=min(mar-i,len[2*po-i]);
else
len[i]=1;//i在mar右边那就只能自己弄了
while(aa[i-len[i]]==aa[i+len[i]])len[i]++;
if(len[i]+i>mar)//更新已扩展最右边那个点和以它为最长回文的中点
{
mar=len[i]+i;
po=i;
}
ans=max(ans,len[i]);
}
return ans-1;
}
int main()
{
int k=1;
while(scanf("%s",a)!=-1)
{
if(strcmp(a,"END")==0)
break;
int lena=INIT(a);
int ans=MANACHER(aa,lena);
printf("Case %d: %d\n",k++,ans);
}
return 0;
}