lightoj 最长回文字符串 1258 (KMP&manacher)

来源:互联网 发布:最火的韩网络剧短剧 编辑:程序博客网 时间:2024/05/20 18:48

最长回文字符串

Description

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

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;char a[1000010];char b[1000010];int p[1000010];int l;void getp(){int i=0,j=-1;p[i]=j;while(i<l){if(j==-1||b[i]==b[j]){i++;j++;p[i]=j;}elsej=p[j];}}int kmp(){getp();int i=0,j=0;while(i<l){if(j==-1||b[j]==a[i]){i++;j++;}elsej=p[j];}return j;}int main(){int t;int T=1;int i,j;scanf("%d",&t);while(t--){scanf("%s",a);strcpy(b,a);l=strlen(a);//strrev(b);//太坑了。。。交了十几遍一直是CE,strrev函数不能被识别,还是用reverse函数吧。 reverse(b,b+l);int s=kmp();printf("Case %d: %d\n",T++,l+l-s);}return 0;}


//Manachar解


 

#include<stdio.h>#include<string.h>#define N 1000010#include<algorithm>using namespace std;char s[N<<1];char a[N];int p[N<<1];int mm;int manacher(){int l=strlen(s),i;int r=1,m=1;int ans=0;mm=0;memset(p,0,sizeof(p));p[1]=p[0]=1;for(i=2;i<l;i++){if(r>i)p[i]=min(p[m*2-i],r-i);elsep[i]=1;while(s[i-p[i]]==s[i+p[i]])p[i]++;if(p[i]+i>r){r=p[i]+i;m=i;}ans=max(ans,p[i]);if(r==l)mm=max(mm,p[i]-1);}return ans-1;}int main(){int t,T=1;int i,j;scanf("%d",&t);while(t--){scanf("%s",a);int l=strlen(a);s[0]='@';for(i=0;i<l;i++){s[i*2+1]='#';s[i*2+2]=a[i];}s[i*2+1]='#';s[i*2+2]='\0';int ans=manacher();if(ans==l)printf("Case %d: %d\n",T++,l);elseprintf("Case %d: %d\n",T++,l+l-mm);}return 0;}


 

0 0
原创粉丝点击