Extend to Palindrome - UVa 11475 Manacher算法

Problem E

Extend to Palindromes

Time Limit : 3 seconds

 

 

 

Your task is, given an integer N, to make a palidrome (word that reads the same when you reverse it) of length at least N. Any palindrome will do. Easy, isn't it? That's what you thought before you passed it on to your inexperienced team-mate. When the contest is almost over, you find out that that problem still isn't solved. The problem with the code is that the strings generated are often not palindromic. There's not enough time to start again from scratch or to debug his messy code. Seeing that the situation is desperate, you decide to simply write some additional code that takes the output and adds just enough extra characters to it to make it a palindrome and hope for the best. Your solution should take as its input a string and produce the smallest palindrome that can be formed by adding zero or more characters at its end.

 

 

 

Input

 

 

 

 

Input will consist of several lines ending in EOF. Each line will contain a non-empty string made up of upper case and lower case English letters ('A'-'Z' and 'a'-'z'). The length of the string will be less than or equal to 100,000.

 

 

 

 

 

 

 

Output

 

 

 

For each line of input, output will consist of exactly one line. It should contain the palindrome formed by adding the fewest number of extra letters to the end of the corresponding input string.

 

 

 

 

 

 

 

Sample Input

Sample Output

 

 

 

 

 

aaaa
abba
amanaplanacanal
xyz

aaaa
abba
amanaplanacanalpanama
xyzyx


题意:在字符串末端添加最少的字符使其成为回文串。

思路:manacher预处理一下,之后扫一遍找到能直到最后都回文的位置输出即可


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
#define MAXN  110010
int len,llen,p[MAXN*2],pp[MAXN],ans;
char s[MAXN],ss[MAXN*2];
void manacher()
{
    int id=0,mx=0;
    for(int i=2;i<=llen;i++){
        if(mx>i){
            p[i]=min(p[2*id-i],mx-i);
        }else 
            p[i]=1;
        while(ss[i+p[i]]==ss[i-p[i]]) p[i]++;
        if(p[i]+i>mx){
            mx=p[i]+i;
            id=i;
        }
        ans=max(ans,p[i]);
    }
}
int main()
{
    while(~scanf("%s",s)){
        memset(p,0,sizeof(p));
        len=strlen(s);
        llen=2*len+1;
        ans=0;
        for(int i=0;i<=len;i++){
            ss[2*i+2]=s[i];
            ss[2*i+1]='#';
        }
        ss[0]='&';
        manacher();
		for(int i=1;i<=llen;i++){
			if(i+p[i]-1==llen){
				for(int k=1;k<=llen;k++)
					if(ss[k]!='#')
						printf("%c",ss[k]);
				for(int k=i-p[i]+1;k>=1;k--)
					if(ss[k]!='#')
						printf("%c",ss[k]);
				puts("");
				break;
			}
		}
    }
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值