题目链接:http://lightoj.com/volume_showproblem.php?problem=1258
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.
题目大意: 给你一串字符串,问你最少在字符串的尾部添加几个字符,使该串变成回文串(左右读起来一样);
解析: O(n) 回文子串(Manacher)算法 灵活运用,只是条件换下,当时比赛时竟然没做出来,听大牛讲后才明白,还是自己做题比较少吧!
代码如下:
#include<iostream>
#include<algorithm>
#include<map>
#include<string>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#define N 3000009
using namespace std;
const int inf = 0x3f3f3f3f;
const int mod = 1000003;
int dp[N];
char s[N];
int main()
{
int t, i, cnt = 0;
cin >> t;
while(t--)
{
scanf(" %s", s);
int len = strlen(s);
for(i = len; i >= 0; i--)
{
s[i*2+1] = s[i];
s[i*2] = '#';
}
int mx = 0, id = 0, ans = 0;
for(i = 0; s[i]; i++)
{
dp[i] = mx > i ? min(dp[id*2-i], mx-i) : 1;
while(i - dp[i] >= 0 && s[i- dp[i]] == s[i + dp[i]])
dp[i]++;
if(mx < i + dp[i])
{
mx = i + dp[i];
id = i;
}
if(!s[mx])
{
ans=dp[i];
break;
}
}
printf("Case %d: %d\n", ++cnt, 2 * len - (ans - 1));
}
return 0;
}