uva11475

来源:互联网 发布:中国数据域名管理 编辑:程序博客网 时间:2024/05/19 22:58

这个题叭。。。

就是求如何用最少的字母组成回文字符串,然后输出这个字符串。

hash。。。。

先按倒序求出各子串的哈希值,然后再正着算子串的哈希值,直到找到哈希值相同的,找到最长的回文串。。。

举例子好了。。

abcdc,先依次求出c,cdc,cdcb,cdcba的哈希值。。然后求abcdc的哈希值。。再去掉a,求出bcdc的哈希值,再求出cdc的哈希值。。然后这时候刚刚算过的哈希值里有这个诶。。

然后就是处理输出就好了。

#include <iostream>#include <cstring>#include <string.h>#include <cstdio>#include <algorithm>using namespace std;const unsigned long long b=100000007;const int maxn=100005;unsigned long long hash1[maxn],hash2[maxn],hash3,temp;int main(){    int n,len;    char str[maxn];    hash1[1]=1;    for(int i=2;i<maxn;i++)        hash1[i]=hash1[i-1]*b;    while(scanf("%s",str+1)!=EOF)    {        len=strlen(str+1);        hash2[0]=0;        for(int i=len;i>0;i--)            hash2[len-i+1]=hash2[len-i]*b+str[i];        temp=0;        for(int i=1;i<=len;i++)            temp=temp*b+str[i];        n=len;        while(n>0&&temp!=hash2[n])        {            temp-=hash1[n]*str[len-n+1];            n--;        }        for(int i=1;i<=len-n;i++)            printf("%c",str[i]);        for(int i=len;i>0;i--)            printf("%c",str[i]);        printf("\n");    }}


0 0
原创粉丝点击