uva11475 - Extend to Palindrome KMP

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 nd 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.
SampleInput
aaaa
abba
amanaplanacanal
xyz
SampleOutput
aaaa
abba
amanaplanacanalpanama
xyzyx











  在一个串后面最少添加几个字符能使这个串变成回文串。

  在KMP匹配的过程中,模版串当前位置是匹配串当前能匹配的最长长度,所以把给的串倒过来当模版串,跟给的串匹配一遍,匹配到最后模版串的位置也就代表着给出的串从后往前回文串的最长长度,再把剩下的输出。

#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<algorithm>
#define INF 0x3f3f3f3f
#define eps 1e-9
#define MAXNODE 105
#define MOD 10000007
#define SIGMA_SIZE 4
typedef long long LL;
using namespace std;

const int MAXN=100010;
const int MAXM=35;

char a[MAXN],b[MAXN];
int next[MAXN];

int KMP(){
    int i=0,j=0,L1=strlen(b),L2=strlen(a);
    while(i<L1&&j<L2){
        if(j==-1||b[i]==a[j]){
            ++i;
            ++j;
        }
        else j=next[j];
    }
    return j;
}

void get_next(){
    int i=0,j=-1,L=strlen(a);
    next[0]=-1;
    while(i<L){
        if(j==-1||a[i]==a[j]){
            if(a[++i]!=a[++j]) next[i]=j;
            else next[i]=next[j];
        }
        else j=next[j];
    }
}

int main(){
    freopen("in.txt","r",stdin);
    while(scanf("%s",b)!=EOF){
        strcpy(a,b);
        int L=strlen(a);
        reverse(a,a+L);
        get_next();
        int k=KMP();
        printf("%s%s\n",b,a+k);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值