hash算法字符串例题
Extend to Palindrome
Your task is, given an integer N, to make a palidrome (word that reads the same when you reverseit) of length at least N. Any palindromewill do. Easy, isn’t it? That’s what you thought before youpassed it on to your inexperienced team-mate. When the contest is almost over, you find out thatthat problem still isn’t solved. The problem with the code is that the strings generated are often notpalindromic. There’s not enough time to start again from scratch or to debug his messy code. Seeingthat the situation is desperate, you decide to simply write some additional code that takes the outputand 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
aaaa
abba
amanaplanacanal
xyz
Sample Output
aaaa
abba
amanaplanacanalpanama
xyzyx
代码
#include <bits/stdc++.h>
using namespace std;
const int p=131;
const int mod=1e9+7;
const int N=1e5+10;
int hash1[N],hash2[N];
char s[N];
int mapp[N]={1};
int main()
{
for(int i=1;i<N;i++) mapp[i]=mapp[i-1]*p; //记录p的次方
while(cin>>s+1)
{
memset(hash1,0,sizeof hash1);
memset(hash2,0,sizeof hash2);
int len=strlen(s+1);
for(int i=1;i<=len;i++) hash1[i]=hash1[i-1]*p+s[i]-'a'; //顺序hash
for(int i=len;i>=1;i--) hash2[i]=hash2[i+1]*p+s[i]-'a'; //逆序hash
if(hash1[len]==hash2[1]) //字符本身已经是回文串了,直接输出continue
{
cout<<s+1<<endl;
continue;
}
int judge=1;
for(int i=1;i<=len;i++)
{
if((hash1[len]-hash1[i-1]*mapp[len-i+1])==hash2[i]) //枚举位置
{
judge=0;
for(int j=1;j<=len;j++) cout<<s[j];
for(int j=i-1;j>=1;j--) cout<<s[j];
break;
}
}
if(judge)
{
for(int i=1;i<=len;i++) cout<<s[i];
for(int i=len-1;i>=1;i--) cout<<s[i];
}
cout<<endl;
}
}