Palindrome. Again Palindrome

来源:互联网 发布:java 四行杨辉三角 编辑:程序博客网 时间:2024/06/07 10:14

1354. Palindrome. Again Palindrome

Time limit: 1.0 second
Memory limit: 64 MB
word is the nonempty sequence of symbols a1a2an. A palindrome is the word a1a2an that is read from the left to the right and from the right to the left the same way (a1a2an = anan−1a1). IfS1 = a1a2an and S2 = b1b2bm, then S1S2 = a1a2anb1b2bm. The input contains some word S1. You are to find a nonempty word S2 of the minimal length that S1S2 is a palindrome.

Input

The first input line contains S1 (it may consist only of the Latin letters). It’s guaranteed that the length of S1 doesn’t exceed 10000 symbols.

Output

S1S2.

Samples

inputoutput
No
NoN
OnLine
OnLineniLnO
AbabaAab
AbabaAababA

/**使用求回文串的算法:Manacher算法**//** 要添加最短的串,使得新形成的串是回文串,    首先,要考虑原串的回文属性,寻找包含末尾的最大回文后缀串,    但是,    要注意,当原串全部回文的时候,需要找最大回文后缀,但不包括开头~    最后,    要注意,当原串长度为1时,直接复制一遍输出即可.**/#include <iostream>#include<cstdio>#include<cstring>using namespace std;#define maxn 50000char s[maxn],p[maxn];int slen[maxn],len;void read(){    scanf("%s",s);    len=strlen(s);    for(int i=1; i<=len; i++)//Manacher的预处理    {        p[(i<<1)-1]='#';        p[i<<1]=s[i-1];    }    p[0]='?';}void Manacher(){    int j,k,maxid=0,id=0;    for(int i=1; p[i]!='\0'; i++)    {        if(maxid>i)            slen[i]=min(maxid-i,slen[2*id-i]);//实质为动态规划        else            slen[i]=1;        while(p[i+slen[i]]==p[i-slen[i]])            slen[i]++;        if(slen[i]+i>maxid)        {            maxid=slen[i]+i;            id=i;        }    }}int deal(){    int maxi=0;    for(int i=strlen(p)-1; i>(strlen(p)+1)/2; i--)//寻找最长的回文后缀,注意中间的判断条件,如果是大于等于那就会找出包含开头的最大回文后缀,会导致错误    {        if(p[i+slen[i]]=='\0')            maxi=i;    }    return maxi;}int main(){    read();    if(len==1)//原串长度为1时,需要特判    {        printf("%s%s",s,s);        return 0;    }    Manacher();    int j=deal();    printf("%s",s);    for(int i=j-slen[j]; i>=1; i--)//计算出要添加的那一段是从哪里开始的        if(p[i]!='#')            printf("%c",p[i]);    printf("\n");    return 0;}


原创粉丝点击