LightOJ 1258 - Making Huge Palindromes【kmp】

来源:互联网 发布:中巴经济走廊意义知乎 编辑:程序博客网 时间:2024/05/16 08:46

1258 - Making Huge Palindromes

PDF (English)StatisticsForum
Time Limit: 1 second(s)Memory Limit: 32 MB

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

Output for Sample Input

4

bababababa

pqrs

madamimadam

anncbaaababaaa

Case 1: 11

Case 2: 7

Case 3: 11

Case 4: 19


给出一个字符串,求得要在最后加几个字符能组成最短的回文字符串,输出这个回文字符串的长度.........

本来想的暴力,后来放弃了,数据太大,然后想到了用kmp算法......


把字符翻转过来,当成模板串,然后再和原串进行匹配,到最后的时候,求出匹配的长度,这个长度也就是在原串中已经构成回文的那部分的最大长度j,然后len-j 是不能匹配的长度,加上len 得到处理后的最短的回文字符串的长度了.........


例如:

12122   

想把它转化为回文的,那么先求出翻转后的字符串

22121

然后就是找原串的后缀和翻转串的前缀的最多匹配的个数了,kmp跑完之后,j就是匹配的个数,本例即为 22 

那就把翻转串的剩下的字符串(长度为len-j)连接在原串上,就得到了最后的回文串结果,长度为len-j+len,也就是2*len-j....

证明完毕!


学的东西一定要会灵活运用,否则就算会了,也很难解决相似的问题....

继续努力吧!


#include<stdio.h>#include<string.h>char x[1000005],y[1000005];int next[1000005],len;void get_next()//逆置的字符串的nextval {len=strlen(x);int i=0,j=-1;next[i]=j;while(i<len){if(j==-1||y[i]==y[j]){++i;++j;if(y[i]!=y[j]){next[i]=j;}else{next[i]=next[j];}}else{j=next[j];}}}int kmp(){int i=0,j=0;get_next();while(i<len){if(j==-1||x[i]==y[j]){++i;++j;}else{j=next[j];}}return 2*i-j;}int main(){int t;//freopen("shuju.txt","r",stdin);scanf("%d",&t);for(int k=1;k<=t;++k){scanf("%s",x);memset(y,0,sizeof(y));int len=strlen(x);for(int i=0;i<len;++i)//翻转{y[i]=x[len-i-1];}printf("Case %d: %d\n",k,kmp());}return 0;}


.










刘可
0 0
原创粉丝点击