UVA 11475 Extend to Palindrome hash

来源:互联网 发布:南京市雨花区网络问政 编辑:程序博客网 时间:2024/06/05 11:20

题意:给出一个字符串,让你添加最少的字符,使其成为回文串。

思路:这个题是求出最长的回文后缀。这里我们可以用字符串hash来做这道题。

            我们从后往前求出后缀的从前向后和从后向前的子串的hash值,如果hash值相同,说明该位置是回文串。

代码如下:

#include <cstdio>#include <algorithm>#include <cstring>using namespace std;const int MAX = 200010;char str[MAX];int main(void){    //freopen("input.txt","r",stdin);    while(scanf("%s",str) != EOF){        int len = strlen(str);        unsigned int pre = 0, suf = 0;        unsigned int MAGIC = 233,pow = 1;        int maxlen = 0;        for(int i = len - 1; i >= 0; --i){            pre = pre + str[i] * pow;            pow *= MAGIC;            suf = suf * MAGIC + str[i];            if(pre == suf)                maxlen = i;        }        printf("%s",str);        for(int i = maxlen - 1; i >= 0; --i)            putchar(str[i]);        putchar('\n');    }    return 0;}


0 0
原创粉丝点击