1.题目
A string is said to be a palindrome if it remains same when read backwards. So, ‘abba’, ‘madam’ both are palindromes, but ‘adam’ is not.
Now you are given a non-empty string S, containing only lowercase English letters. The given string may or may not be palindrome. Your task is to make it a palindrome. But you are only allowed to add characters at the right side of the string. And of course you can add any character you want, but the resulting string has to be a palindrome, and the length of the palindrome should be as small as possible.
For example, the string is ‘bababa’. You can make many palindromes including
bababababab
babababab
bababab
Since we want a palindrome with minimum length, the solution is ‘bababab’ cause its length is minimum.
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with a line containing a string S. You can assume that 1 ≤ length(S) ≤ 106.
Output
For each case, print the case number and the length of the shortest palindrome you can make with S.
Sample Input
4
bababababa
pqrs
madamimadam
anncbaaababaaa
Sample Output
Case 1: 11
Case 2: 7
Case 3: 11
Case 4: 19
Note
Dataset is huge, use faster I/O methods.
2.代码
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=3*1e6+66;
char str[MAXN],S[MAXN]; int p[MAXN];
int Manacher(char *S)
{
int id=0,mx=0,i=0,ans=0;
int len=strlen(S);
for(i=1;S[i];++i){
p[i]=mx>i?min(mx-i,p[(id<<1)-i]):1;
while(S[i+p[i]]==S[i-p[i]]) ++p[i];
if(i+p[i]>mx) {
mx=i+p[i];
id=i;
}
if(mx>(len-1)) return p[id]-1;
}
}
int main()
{
int T,i,Kase=0;
scanf("%d",&T);
while(T--)
{
scanf("%s",str);
S[0]='$'; S[1]='#';
for(i=0;str[i];++i)
{
S[(i+1)<<1]=str[i];
S[(i+1)*2+1]='#';
}
S[(i+1)<<1]='\0';
int ans=Manacher(S),len=strlen(str);
printf("Case %d: %d\n",++Kase,len-ans+len);
}
return 0;
}