首页 > 其他 > 详细

D - 楼下水题(kmp)

时间:2015-10-24 23:39:55      阅读:508      评论:0      收藏:0      [点我收藏+]
D - 楼下水题
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu

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

题解:

kmp,找右侧添加若干字母使这个字符串回文;

代码:

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<cmath>
 6 #include<map>
 7 #include<vector>
 8 #include<stack>
 9 #include<queue>
10 using namespace std;
11 const int INF=0x3f3f3f3f;
12 const int MAXN=1000010;
13 char s[MAXN],m[MAXN];
14 int p[MAXN];
15 void getp(){
16     int i=0,j=-1;
17     p[0]=-1;
18     while(m[i]){
19         if(j==-1||m[i]==m[j]){
20             i++;j++;
21             p[i]=j;
22         }
23         else j=p[j];
24     }
25 }
26 int kmp(){
27     getp();
28    // for(int i=0;s[i];i++)printf("%d ",p[i]);puts("");
29     int i=0,j=0;
30     int mx=0,temp=0;
31     while(m[i]){
32         if(j==-1||m[j]==s[i]){
33             i++;j++;
34         }
35         else{
36             j=p[j];
37         }
38     }
39     return j;
40 }
41 int main(){
42     int T,flot=0;
43     scanf("%d",&T);
44     while(T--){
45         scanf("%s",s);
46         strcpy(m,s);
47         int len=strlen(s);
48         reverse(m,m+len);
49     //    puts(m);
50         //puts(s);
51         printf("Case %d: %d\n",++flot,len+len-kmp());
52     }
53     return 0;
54 }

 

D - 楼下水题(kmp)

原文:http://www.cnblogs.com/handsomecui/p/4907830.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!