Making Huge Palindromes
LightOJ - 1258A string is said to be a palindrome if it remains same when read backwards. So, 'abba', 'madam' both are palindromes, but 'adam' is not.
Now you are given a non-empty string S, containing only lowercase English letters. The given string may or may not be palindrome. Your task is to make it a palindrome. But you are only allowed to add characters at the right side of the string. And of course you can add any character you want, but the resulting string has to be a palindrome, and the length of the palindrome should be as small as possible.
For example, the string is 'bababa'. You can make many palindromes including
bababababab
babababab
bababab
Since we want a palindrome with minimum length, the solution is 'bababab' cause its length is minimum.
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with a line containing a string S. You can assume that 1 ≤ length(S) ≤ 106.
For each case, print the case number and the length of the shortest palindrome you can make with S.
4
bababababa
pqrs
madamimadam
anncbaaababaaa
Case 1: 11
Case 2: 7
Case 3: 11
Case 4: 19
Dataset is huge, use faster I/O methods.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 1e6+100;
char s[MAXN];
char News[MAXN<<1];
int len[MAXN<<1];
bool post[MAXN];
int init(int n){
int i,cnt = 0;
News[cnt++] = '@';
News[cnt++] = '#';
for(i = 0; i < n; i++){
News[cnt++] = s[i];
News[cnt++] = '#';
}
News[cnt++] = '$';
News[cnt] = '\0';
return cnt-1;
}
void Manacher(int n){
int i,mx = 0,po = 0;
memset(post,false,sizeof(post));
for(i = 1; i < n; i++){
if(mx > i)
len[i] = min(mx-i,len[2*po-i]);
else
len[i] = 1;
while(News[i-len[i]] == News[i+len[i]])
len[i]++;
if(i+len[i] == n)
post[len[i]-1] = true;
if(i+len[i] > mx){
mx = i+len[i];
po = i;
}
}
}
int main(){
int t,cas = 0;
scanf("%d",&t);
while(t--){
scanf("%s",s);
int n = strlen(s);
n = init(n);
Manacher(n);
n = strlen(s);
int i,flag = 0;
printf("Case %d: ",++cas);
for(i = n; i >= 2; i--){
if(post[i]){
flag = 1;
printf("%d\n",n+(n-i));
break;
}
}
if(!flag){
printf("%d\n",n+n-1);
}
}
return 0;
}
本文介绍了一种算法,用于将任意给定的字符串通过在右侧添加字符的方式转换成尽可能短的回文串。该算法利用了Manacher算法来找出最长的回文子串,并在此基础上构建最小长度的回文串。
593

被折叠的 条评论
为什么被折叠?



