UVA 11475 Extend to Palindrome(hash)题解

题意:问你最少加几个字母使所给串变成回文串。

思路:一开始打算将正序和逆序都hash,然后用提取前缀后缀的方法来找,但是RE了,debug失败遂弃之。后来发现可以直接hash,一边hash一边比较。我们只需找出正序hash值和逆序hash相同的最长串就是最长回文子串。

代码:

#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<cstring>
#include<string>
#include<sstream>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define ll long long
#define ull unsigned long long
using namespace std;
const int maxn = 200000+10;
const int seed = 131;
const int MOD = 100013;
const int INF = 0x3f3f3f3f;
char s[maxn];
int main(){
    while(scanf("%s", s + 1) != EOF){
        int len = strlen(s + 1);
        ull suf = 0,pre = 0,bit = 1,Max = 1;
        for(int i = len; i >= 1; i--){
            pre = pre * seed + s[i];    //倒序前缀
            if(i != len) bit *= seed;
            suf = suf + bit * s[i];   //正序后缀
            if(pre == suf){
                Max = len - i + 1;
            }
        }
        for(int i = 1; i <= len; i++)
            printf("%c", s[i]);
        for(int i = len - Max; i >= 1; i--)
            printf("%c", s[i]);
        printf("\n");
    }
    return 0;
}
/*
aaaa
abba
amanaplanacanal
xyz
*/

 

posted @ 2018-08-23 14:35  KirinSB  阅读(290)  评论(0编辑  收藏  举报