UVA11475--Extend to Palindrome

来源:互联网 发布:手机上怎样查淘宝积分 编辑:程序博客网 时间:2024/06/05 20:51

Your task is, given an integer N, to make a palidrome (word that reads the same when you reverse it) of length at least N. 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.

Input

Input will consist of several lines ending in EOF. Each line will contain a non-empty string made up of upper case and lower case English letters ('A'-'Z' and 'a'-'z'). The length of the string will be less than or equal to 100,000.

Output

For each line of input, output will consist of exactly one line. It should contain the palindrome formed by adding the fewest number of extra letters to the end of the corresponding input string.

Sample Input

Sample Output

aaaa
abba
amanaplanacanal
xyz

aaaa
abba
amanaplanacanalpanama
xyzyx

题意:在所给的字符串后添加最小字符形成回文串。

思路:建立2个Hash数组,一个从前往后Hash,一个从后往前Hash。

           枚举需要添加的字符数i,则后面len-i长度为一个回文串。根据回文串长度的奇偶,分类讨论。

           判断对称中心两段的字串是否回文,只需要左端字串的正哈希函数和右断字串的反哈希函数相等。

#include <iostream>#include <cstdio>#include <cstring>using namespace std;#define maxn 100080unsigned long long Hash1[maxn],Hash2[maxn],mi[maxn];char str[maxn];void Hash_Get(int n){Hash1[n] = 0;for(int i = n-1;i >= 0;i--)Hash1[i] = Hash1[i+1]*3 + str[i];Hash2[0] = str[0];for(int i = 1;i <= n;i++)Hash2[i] = Hash2[i-1]*3 + str[i];}void init(){mi[0] = 1;for(int i = 1;i < maxn;i++)mi[i] = mi[i-1]*3;}int main(){//freopen("in.txt","r",stdin);init();while(scanf("%s",str)!=EOF){int len = strlen(str);Hash_Get(len);int ans = 100080,pos;for(int i = 0;i < len;i++){if((len-i) & 1){pos = i+(len-i)/2;if(Hash1[i] - Hash1[pos]*mi[pos-i] != Hash2[len-1] - Hash2[pos]*mi[len-1-pos])continue;else {ans = i;break;}}else {if(str[i+((len-i)>>1)] != str[i+(len-i)/2-1])continue;if(Hash1[i] - Hash1[i+(len-i)/2-1]*mi[(len-i)/2-1] != Hash2[len-1] - Hash2[i+((len-i)>>1)]*mi[len-1-(i+((len-i)>>1))])continue;else {ans = i;break;}}}if(ans == maxn)ans = len - 1;printf("%s",str);for(int i = ans-1;i >= 0;i--)printf("%c",str[i]);printf("\n");}return 0;}


0 0