字符串hash模板

typedef unsigned long long ull;
struct My_Hash
{
    ull base=131;
    ull p[N],ha[N];
    void Insert(char s[])
    {
        int len=strlen(s+1);
        p[0]=1,ha[0]=0;
        for(int i=1;i<=len;i++)
        {
            p[i]=p[i-1]*base;
            ha[i]=ha[i-1]*base+(ull)s[i];
        }
    }
    ull gethash(int l,int r)
    {
        return (ull)ha[r]-ha[l-1]*p[r-l+1];
    }
}S;
int main()
{
    char s[N];
    cin>>s+1;
    S.Insert(s);
    int T;
    cin>>T;
    while(T--)
    {
        int l,r;
        cin>>l>>r;
        cout<<S.gethash(l,r)<<endl;
    }

    return 0;
}
posted @ 2020-07-13 23:48  xyq0220  阅读(99)  评论(0编辑  收藏  举报