ACM-ICPC 2018 南京赛区网络预赛-I:Skr(manacher+Hash)

版权声明:http://blog.csdn.net/Mitsuha_。 https://blog.csdn.net/Mitsuha_/article/details/82313627

A number is skr, if and only if it’s unchanged after being reversed. For example, “12321”, “11” and “1” are skr numbers, but “123”, “221” are not. FYW has a string of numbers, each substring can present a number, he wants to know the sum of distinct skr number in the string. FYW are not good at math, so he asks you for help.

Input
The only line contains the string of numbers S.

It is guaranteed that 1 S [ i ] 9 , the length of S is less than 2000000.

Output
Print the answer modulo 1000000007.

样例输入1
111111
样例输出1
123456
样例输入2
1121
样例输出2
135

思路:利用manacher求出所有子串然后插入hash表统计答案即可。

#include<bits/stdc++.h>
using namespace std;
const int MAX=2e6+10;
const int MOD=1e9+7;
const int Hashsize=2000003;
const unsigned long long p=131;
typedef long long ll;
typedef unsigned long long ull;
struct lenka
{
    int next;
    ull val;
}ed[MAX];
int head[MAX],cnt=0;
ull f[MAX],sum[MAX];
ll pre[MAX],fac[MAX];
ll ans=0;
void Insert(int x,int y)
{
    ull tot=sum[y]-sum[x-1]*f[y-x+1];
    for(int i=head[tot%Hashsize];i!=-1;i=ed[i].next)
    {
        if(tot==ed[i].val)return;
    }
    ans+=(pre[y]-pre[x-1]*fac[y-x+1]%MOD+MOD)%MOD;
    ans%=MOD;
    ed[cnt].next=head[tot%Hashsize];
    ed[cnt].val=tot;
    head[tot%Hashsize]=cnt++;
}
char s[MAX];
int len[MAX];
int main()
{
    fac[0]=1;
    for(int i=1;i<=2e6;i++)fac[i]=fac[i-1]*10%MOD;
    scanf("%s",s+1);
    int n=strlen(s+1);
    f[0]=1;
    for(int i=1;i<=n;i++)
    {
        f[i]=f[i-1]*p;
        sum[i]=sum[i-1]*p+s[i];
        pre[i]=(pre[i-1]*10%MOD+s[i]-'0')%MOD;
    }
    memset(head,-1,sizeof head);
    cnt=0;
    int mx=0,x=0;
    for(int i=1;i<=n;i++)
    {
        Insert(i,i);
        if(mx>i)len[i]=min(mx-i,len[2*x-i]);
        while(i+len[i]+1<=n&&s[i+len[i]+1]==s[i-len[i]-1])
        {
            Insert(i-len[i]-1,i+len[i]+1);
            len[i]++;
        }
        if(i+len[i]>mx)
        {
            mx=i+len[i];
            x=i;
        }
    }
    mx=x=0;
    memset(len,0,sizeof len);
    memset(head,-1,sizeof head);
    cnt=0;
    for(int i=2;i<=n;i++)
    {
        if(mx>i)len[i]=min(mx-i+1,len[2*x-i]);
        while(i+len[i]<=n&&s[i+len[i]]==s[i-len[i]-1])
        {
            Insert(i-len[i]-1,i+len[i]);
            len[i]++;
        }
        if(i+len[i]-1>mx)
        {
            mx=i+len[i]-1;
            x=i;
        }
    }
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mitsuha_/article/details/82313627