又get了一种新的Hash方法。Seed取素数可以降低取余相同的概率,目测是这样的。
Hash[i] = Hash[i+1] *Seed + s[i]-'a'。
那么 [i,i+l-1]这一段的Hash值即为Hash[i] - Hash[i+l]*Seek^l。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <ctime>
#include <iomanip>
#pragma comment(linker, "/STACK:1024000000");
#define EPS (1e-6)
#define LL long long
#define ULL unsigned long long
#define _LL __int64
#define INF 0x3f3f3f3f
#define Mod 1000000007
#define Seed 31
using namespace std;
ULL hash[100010];
ULL K;
char s[100010];
map<ULL,int> ma;
int main()
{
int n,m,l,i,j;
while(scanf("%d %d",&m,&l) != EOF)
{
scanf("%s",s);
for(n = strlen(s), i = n-1 ,hash[n] = 0;i >= 0; --i)
hash[i] = hash[i+1]*Seed + (s[i]-'a'+1);
for(K = Seed,i = 2;i <= l; ++i)
K *= Seed;
// for(i = 0;i < n-l; ++i)
// printf("i = %d hash = %I64u\n",i,hash[i]-hash[i+l]*K[l]);
ULL tmp;
int anw = 0;
for(i = 0;i < l && m*l+i < n; ++i)
{
ma.clear();
for(j = i;j < m*l+i;j += l)
ma[hash[j] - hash[j+l]*K]++;
if(ma.size() == m)
anw++;
for(j = m*l+i;j+l <= n; j += l)
{
ma[hash[j-m*l]-hash[j-m*l+l]*K]--;
if(ma[hash[j-m*l]-hash[j-m*l+l]*K] == 0)
ma.erase(hash[j-m*l]-hash[j-m*l+l]*K);
ma[hash[j] - hash[j+l]*K]++;
if(ma.size() == m)
anw++;
}
}
printf("%d\n",anw);
}
return 0;
}