码迷,mamicode.com
首页 > 其他好文 > 详细

LightOJ 1258 Making Huge Palindromes (回文&KMP)

时间:2015-08-14 11:49:37      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

http://lightoj.com/volume_showproblem.php?problem=1258

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.

首先原串+翻转过来的串必然是一个回文串,但是二者在中间可以“融合”,而KMP算法恰好可以求出最大融合长度。

所以看翻转过来的串能匹配多少原串即可,答案就是len+(len-匹配个数)。

#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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LightOJ 1258 Making Huge Palindromes (回文&KMP)

标签:

原文地址:http://blog.csdn.net/acm_10000h/article/details/47658095

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!