字符串哈希模板(待修改)

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1610612741;
const int base = 17;
const int maxn = 1e6+10;
char s[maxn];
ll ha[maxn];
int len;
ll ans;
inline ll qpow(int a,int b)
{
    ll ret=1;
    while(b)
    {
        if (b&1) ret=ret*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return ret;
}
inline ll hhash(int x)
{
    return (ha[x-1]*base+s[x])%mod;
}
inline ll halr(int l,int r)
{
    ll t;
    t=ha[l-1]%mod*qpow(base,r-l+1)%mod;
    return ((ha[r]-t)%mod+mod)%mod;
}
inline ll fun(int x)
{
    int l,r,ret=0;
    l=x;

    r=len-1;int mid,k;
    while(l<=r)
    {
        mid=(l+r)>>1;
        if(ha[mid-x]==halr(x,mid))
        {
            k=mid;
            if(ha[mid-x+1]!=halr(x,mid+1))
            {
                ret=mid-x+1;
                k=mid-x+1;
                //cout<<mid<<endl;
                break;
            }
            l=mid+1;
        }
        else
        {
            r=mid-1;
        }
    }
    if (k!=len-1) ret++;
    return ret;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ans=0;
        memset(ha,0,sizeof(ha));
        scanf("%s",s);
        len=strlen(s);
        ha[0]=s[0];
        for (register int i=1;i<len;i++)
        {
            ha[i]=hhash(i);
        }
       // cout<<ha[2]<<endl;
       // cout<<halr(3,3)<<endl;
        for (register int i=1;i<len;i++)
        {
            ans+=fun(i);
        }
        printf("%lld
",ans-1);
    }
    return 0;
}
/*2
3
_Happy_New_year_
ywwyww
zjczzzjczjczzzjc
*/
原文地址:https://www.cnblogs.com/ztdf123/p/11304960.html