http://lightoj.com/volume_showproblem.php?problem=1258
A string is said the palindrome if it remains same when read backwards. So, ' Abba ', ' Madam ' both was palindromes, but ' Adam ' was not.
Now is given a non-empty string S, containing only lowercase 中文版 letters. The given string may or could be palindrome. Your task is to make it a palindrome. Allowed to add characters at the right side of the string. And of course can add any character your want, but the resulting string have to be a palindrome, and the length of the P Alindrome 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 it's length is minimum.
Input
Input starts with an integer T (≤10), denoting the number of test cases.
Each case is 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 your 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
The Dataset is huge, and the use faster I/O methods.
First the original string + flips over the string must be a palindrome string, but the two can be "fused" in the middle, and the KMP algorithm can find the maximum fusion length.
So look at the number of flip over the string can match how many original string can, the answer is len+ (len-match number).
#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;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Lightoj 1258 Making Huge palindromes (palindrome &kmp)