UVA 11475 Extend to Palindrome KMP

Posted Meek

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA 11475 Extend to Palindrome KMP相关的知识,希望对你有一定的参考价值。

题目链接: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的主要内容,如果未能解决你的问题,请参考以下文章

UVa 11475 - Extend to Palindrome

UVA 11475 Extend to Palindrome(hash)题解

Extend to Palindrome UVA - 11475 (后缀数组)

UVA 11475 Extend to Palindrome(后缀数组+ST表)

UVA 11475 后缀数组/KMP

Manncher算法