題目鏈接:http://poj.org/problem?id=1200
RKhash 把每個子串轉爲nc進制再hash
RKhash 詳解:http://www.cnblogs.com/cobbliu/archive/2012/05/24/2517151.html
#include <cstdio>
#include <cstring>
const int N = 16666666;
bool hash[N];
int letr[26];
char s[N];
int pow(int a, int b)
{
int r = 1, base = a;
while(b) {
if(b & 1) r *= base;
base *= base;
b >>= 1;
}
return r;
}
int main()
{
int n, nc, t = 0;
while(~scanf("%d%d", &n, &nc)) {
memset(hash, 0, sizeof(hash));
memset(letr, 0, sizeof(letr));
scanf("%s", s);
int len = strlen(s), pw = pow(nc, n-1), ans = 0;
for(int i = 0, j = 0; i < len && j != nc; i++) {
if(!letr[s[i]-'a']) letr[s[i]-'a'] = j++;
}
for(int i = 0; i < n - 1; i++) t = t * nc + letr[s[i] - 'a'];
for(int i = n - 1; i < len; i++) {
t = t * nc + letr[s[i] - 'a'];
if(!hash[t]) {
hash[t] = 1;
ans++;
}
t = t - pw * letr[s[i-n+1] - 'a'];
}
printf("%d\n", ans);
}
return 0;
}