light oj 1258

Time Limit: 1000MSMemory Limit: 32768KB64bit IO Format: %lld & %llu

Submit Status uDebug

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

Hint

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 2000100;
char str[N];
int p[N];


int main()
{
    int t, ncase=1;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s",str);
        int len=strlen(str);
        for(int i=len;i>=0;i--)
        {
            str[i+i+2]=str[i];
            str[i+i+1]='#';
        }
        str[0]='*';
        int id=0, num=-1;
        memset(p,0,sizeof(p));
        for(int i=2;i<2*len+1;i++)
        {
            if(id+p[id]>i)
            {
                p[i]=min(p[id-(i-id)],p[id]-(i-id));
            }
            else
            {
                p[i]=1;
            }
            while(str[i+p[i]]==str[i-p[i]]) p[i]++;
            if(i+p[i]>id+p[id])
            {
                id=i;
            }
            if(i+p[i]==2*len+2)
            {
                num=p[i]-1;
                break;
            }
        }
        if(num==-1)
        {
            printf("Case %d: %d\n",ncase++,len+len-1);
        }
        else
        {
            printf("Case %d: %d\n",ncase++,len+len-num);
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值