题意:问你最少加几个字母使所给串变成回文串。
思路:一开始打算将正序和逆序都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 = +;
const int seed = ;
const int MOD = ;
const int INF = 0x3f3f3f3f;
char s[maxn];
int main(){
while(scanf("%s", s + ) != EOF){
int len = strlen(s + );
ull suf = ,pre = ,bit = ,Max = ;
for(int i = len; i >= ; i--){
pre = pre * seed + s[i]; //倒序前缀
if(i != len) bit *= seed;
suf = suf + bit * s[i]; //正序后缀
if(pre == suf){
Max = len - i + ;
}
}
for(int i = ; i <= len; i++)
printf("%c", s[i]);
for(int i = len - Max; i >= ; i--)
printf("%c", s[i]);
printf("\n");
}
return ;
}
/*
aaaa
abba
amanaplanacanal
xyz
*/