当前位置 : 主页 > 手机开发 > ROM >

Making Huge Palindromes LightOJ - 1258

来源:互联网 收集:自由互联 发布时间:2021-06-10
题目链接: LightOJ - 1258 1258 - Making Huge Palindromes PDF (English) Statistics Forum 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‘

 

题目链接:LightOJ - 1258

1258 - Making Huge Palindromes   PDF (English) Statistics Forum 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.

 

写个博客证明我学过马拉车...

题意:只能在串末尾加字母,问能形成的最短的回文串的长度。

思路:因为只能在末尾加字母,那么可以知道最后添加的那个字母肯定和第一个字母一样,倒数第二个添加的和第二个字母一样...最坏情况下答案是$2len$

能影响答案的只有末尾段,就是如果末尾有一段是回文的,那么我们不需要去添字母和这一段匹配了,所以求个最长的回文串并且到了最后一个字母的长度$x$。

答案就是$2len-x$

分享图片
#include <bits/stdc++.h>
using namespace std;

const int N = 2e6 + 10;
char s[N], mp[N];
int ma[N];

int main() {
    int T;
    int kase = 0;
    scanf("%d", &T);
    while (T--) {
        scanf("%s", s);
        int len = strlen(s);
        int l = 0;
        mp[l++] = $; mp[l++] = #;
        for (int i = 0; i < len; i++) {
            mp[l++] = s[i];
            mp[l++] = #;
        }
        mp[l] = 0;
        int mx = 0, id = 0;
        int ans = 0;
        for (int i = 0; i < l; i++) {
            ma[i] = mx > i ? min(mx - i, ma[2 * id - i]) : 1;
            while (i - ma[i] >= 0 && mp[i + ma[i]] == mp[i - ma[i]]) ma[i]++;
            if (i + ma[i] > mx) {
                mx = i + ma[i];
                id = i;
            }
            if (ma[i] + i == l) ans = max(ans, ma[i] - 1);
        }
        printf("Case %d: %d\n", ++kase, 2 * len - ans);
    }
    return 0;
}
View Code
网友评论