http://lightoj.com/volume_showproblem.php?problem=1258
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 |
Note
Dataset is huge, use faster I/O methods.
首先原串+翻转过来的串必然是一个回文串,但是二者在中间可以“融合”,而KMP算法恰好可以求出最大融合长度。
所以看翻转过来的串能匹配多少原串即可,答案就是len+(len-匹配个数)。
#include<bits/stdc++.h> using namespace std; const int mx=100007; char t[mx],p[mx]; int f[mx],len; void getfail() { f[0]=f[1]=0; for(int i=1;p[i];i++) { int j=f[i]; while(j&&p[i]!=p[j]) j=f[j]; f[i+1]=(p[i]==p[j]?j+1:0); } } int findd() { getfail(); int j=0; for(int i=0;t[i];i++) { while(j&&p[j]!=t[i]) j=f[j]; if(p[j]==t[i]) ++j; } return (len<<1)-j; } int main() { //freopen("in.txt","r",stdin); int tt; scanf("%d",&tt); getchar(); for(int cas=1;cas<=tt;cas++) { gets(t); len=strlen(t); reverse_copy(t,t+len,p); p[len]=0; printf("Case %d: %d\n", cas, findd()); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。