首页 > 其他 > 详细

UVA 11475 Extend to Palindrome KMP

时间:2017-07-23 23:46:40      阅读:322      评论:0      收藏:0      [点我收藏+]

题目链接:https://vjudge.net/problem/UVA-11475

题意:

  给你一个串S

  你可以在结尾补充任意数量字母,问最少数量使得新串是回文串

题解:

  KMP

  将S串倒置跑KMP

#include<bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
#define ls i<<1
#define rs ls | 1
#define pii pair<int,int>
#define MP make_pair
typedef long long LL;
typedef unsigned long long ULL;
const long long INF = 1e18+1LL;
const double pi = acos(-1.0);
const int N = 2e5+10, M = 1e3+20,inf = 2e9;

int fail[N];
char a[N],b[N];
int len;
void build_fail() {
    memset(fail,-1,sizeof(fail));
    int j = -1;
    fail[0] = -1;
    for(int i = 1; i < len; ++i) {
        while(j!=-1 && b[i] != b[j+1]) j = fail[j];
        if(b[j+1] == b[i]) j++;
        fail[i] = j;
    }
}
int kmp() {
    int j = -1;
    for(int i = 0; i < len; ++i) {
        while(j!=-1 && a[i]!=b[j+1]) j = fail[j];
        if(b[j+1] == a[i]) j++;
    }
    return j+1;
}
int main() {
    while(scanf("%s",a)!=EOF) {
        len = strlen(a);
        for(int i = 0; i < len; ++i)
            b[len - i - 1] = a[i];
        build_fail();
        cout<<a;
        for(int i = kmp(); i < len; ++i) printf("%c",b[i]);
        printf("\n");
    }
    return 0;
}

 

UVA 11475 Extend to Palindrome KMP

原文:http://www.cnblogs.com/zxhl/p/7226561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!