LightOJ 1258

来源:互联网 发布:淘宝售后率高 编辑:程序博客网 时间:2024/06/06 00:07

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

题意:就是求将所给字符串变成回文字符串后的最小长度

manacher求最大回文字符串,2*l-最大回文字符串就是所求值

代码:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 1e6 + 1e6 + 100;char str[N];int f[N], pos;int manacher(char *s, int len) {    int id = 0;    for (int i = len; i >= 0; i--) {        s[i + i + 2] = s[i];        s[i + i + 1] = '#';    }    s[0] = '$';    int len1 = 2 * len + 1;    for (int i = 2; i < len1; i++) {        if (f[id] + id > i) f[i] = min(f[id * 2 - i], f[id] - i + id);        else f[i] = 1;        while (s[i + f[i]] == s[i - f[i]]) ++f[i];        if (f[i] + i > id + f[id]) id = i;        if (f[i] + i >= len1)            return len1 - i;    }}//求最大回文字符串int main() {    int t, cas = 1;    scanf("%d", &t);    while (t--) {        scanf("%s", str);        int len = strlen(str);        int res = manacher(str, len);        printf("Case %d: %d\n", cas++, len - res + len);    }    return 0;}

0 0