原题链接,进去比较慢
Description
Your task is, given an integer N, to make a palindrome (word that reads the same when you reverse it) of length at least N (1 <= N <= 100,000). Any palindrome will do.
Easy, isn't it? That's what you thought before you passed it on to your inexperienced team-mate. When the contest is almost over, you find out that that problem still isn't solved. The problem with the code is that the strings generated are often not palindromic. There's not enough time to start again from scratch or to debug his messy code.
Seeing that the situation is desperate, you decide to simply write some additional code that takes the output and adds just enough extra characters to it to make it a palindrome and hope for the best. Your solution should take as its input a string and produce the smallest palindrome that can be formed by adding zero or more characters at its end. The input string will consist of only upper and lower case letters.
Example
Input:
aaaa
abba
amanaplanacanal
xyz
Output:
aaaa
abba
amanaplanacanalpanama
xyzyx
题目大意:
给定一个字符串,要求在尾部添加最少字符使其成为回文串。
题目分析:
我们可以通过求尾部最大回文串, 尾部最大回文子串左边的字符即为要添加的字符, 那么将回文串左边的字符在输出原串后逆序输出即为答案。
求尾部的最大回文子串我们可以用hash和kmp求解,将原串的尾部和翻转后串的头部进行对比,求得最长相同的部分,比如abcdc和翻转后的串cdcba最长相同部分为cdc,那么对应该题答案为abcdc + ba -> abcdcba,使用hash求解时我们也可以倒着预处理,但后面求hash值时要注意。
代码:
hash
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long ull;
const int N = 1e5 + 5;
ull p[N], f[N];
ull ff[N];
char s[N];
char ss[N];
int main()
{
while (scanf("%s", s + 1) != EOF){
int len = strlen(s + 1);
p[0] = 1;
for (int i = 1; i <= len + 1; i ++){
ss[i] = s[i];
}
reverse(ss + 1, ss + len + 1);
for (int i = 1; i <= len; i ++){
f[i] = f[i - 1] * 131 + s[i] - 'a' + 1;
ff[i] = ff[i - 1] * 131 + ss[i] - 'a' + 1;
p[i] = 131 * p[i - 1];
}
int l = 0;
for (int i = len; i >= 0; i --){
if (f[len] - f[len - i] * p[i] == ff[i] - ff[0] * p[i]){
l = i;
break;
}
}
for (int i = 1; i <= len; i ++)printf("%c", s[i]);
for (int i = l + 1; i <= len; i ++)printf("%c", ss[i]);
printf("\n");
}
return 0;
}
kmp
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 5;
int nex[N];
char p[N];
char s[N];
int len;
void cal_next(){
nex[1] = 0;
for (int i = 2, j = 0; i <= len; i ++){
while(j > 0 && p[i] != p[j + 1])j = nex[j];
if (p[i] == p[j + 1])j ++;
nex[i] = j;
}
}
int kmp(){
int i = 1, j = 1;
while (i < len){
if (s[i] == p[j]) i ++, j ++;
else if (j > 1)j = nex[j - 1] + 1;
else i ++;
//cout << j << endl;
}
return j;
}
int main()
{
while(scanf("%s", s + 1) != EOF){
len = strlen(s + 1);
for (int i = 1; i <= len + 1; i ++){
p[i] = s[i];
}
reverse(p + 1, p + len + 1);
cal_next();
int j = kmp();
//cout << j << endl;
printf("%s", s + 1);
for (int i = j + 1; i <= len; i ++)printf("%c", p[i]);
printf("\n");
}
return 0;
}