Here is a piece of code taken from the github repository of Ashish Gupta
Hashs(string &s, int P, int MOD) : P(P), MOD(MOD)
{
int n = s.size();
pows.resize(n+1, 0);
hashs.resize(n+1, 0);
pows[0] = 1;
for(int i=n-1;i>=0;i--)
{
hashs[i]=(1LL * hashs[i+1] * P + s[i] - 'a' + 1) % MOD;
pows[n-i]=(1LL * pows[n-i-1] * P) % MOD;
}
pows[n] = (1LL * pows[n-1] * P)%MOD;
}
int get_hash(int l, int r)
{
int ans=hashs[l] + MOD - (1LL*hashs[r+1]*pows[r-l+1])%MOD;
ans%=MOD;
return ans;
}
I have two doubts here.
- Can’t the loop can be run from 0 to n to generate the hash as given on the CP Algorithms Page. Will it be wrong.
- How is getHash(int l, int r) implemented. Meaning how it is giving the hash value for a given range.