1258 - Making Huge Palindromes
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 |
Note
Dataset is huge, use faster I/O methods.
题意:给出一个字符串,可以在字符串后面增加字符将其变为回文串。问最少增加几个字符原串能变为回文串,输出变为回文串后的字符串的最小长度。
题解:QAQ啊,又是不会。就是个很水的KMP啊。 将原串的后缀与逆序串的前缀相互匹配,求出他们的最长的相同锥长度,再用两个串的总长度(即两个原串的长度)减去最长相同缀长度就能得到所求的回文串长度。
例如:原串: ababb 逆序串:bbaba 将原串的后缀与逆序串的前缀匹配,等到最长相等缀为bb,长度为2,即所求回文串的长度为 2*5-2=8。
具体代码如下:
#include<cstdio>
#include<cstring>
#define max 1000010
char s[max],str[max];
int len,next[max];
void getnext()
{
int i=0,j=-1;
next[0]=-1;
while(i<len)
{
if(j==-1||str[i]==str[j])
next[++i]=++j;
else
j=next[j];
}
}
void kmp()
{
int i=0,j=0;
while(i<len)
{
if(j==-1||s[i]==str[j])
{
i++;
j++;
}
else
j=next[j];
}
printf("%d\n",2*len-j);
}
int main()
{
int t,k=1,i;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
len=strlen(s);
for(i=0;i<len;++i)
str[i]=s[len-1-i];
printf("Case %d: ",k++);
getnext();
kmp();
}
return 0;
}