SCL--字符串hash
2016-04-04 21:02:46
字符串板子贴在这里,借鉴了xiaoxin巨巨的板子~
1:hash结构体,字符串数组是从1开始编号的
const int MOD = 1000000007; struct Hash{ // string : 1-base int B,mod,len,hash[1000010],pw[1000010]; void init(char *s,int tlen,int tB,int tmod){ B = tB,mod = tmod,len = tlen; pw[0] = 1; hash[0] = 0; for(int i = 1; i <= len; ++i){ pw[i] = 1ll * pw[i - 1] * B % mod; hash[i] = (1ll * hash[i-1] * B + s[i] - 'a' + 1) % mod; } } int gethash(int l,int r){ int res = (hash[r] - 1ll * hash[l - 1] * pw[r - l + 1]) % mod; if(res < 0) res += mod; return res; } };
2:具体用法,进制数B的选择为素数,如:173,179,181,271,277 ....
scanf("%s",s + 1); slen = strlen(s + 1); H1.init(s,slen,173,MOD);
3:必要的时候上双hash!