题意:给定一个字符串,找这样的子串数,长为l*m,能分解成m个长为l的不同子串。
做法:算出所有长为l的hash值,分成l组,跑一遍,用map做一下判重。
代码:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
#include <iostream>
using namespace std;
typedef unsigned long long ull;
const int maxn=100007;
ull mhash[maxn];
ull seed=1e9+7;
char str[maxn];
int m, l;
int len;
int main()
{
while(~scanf("%d%d%s", &m, &l, str)){
len=strlen(str);
ull ux=1;
for(int i=1;i<=l;i++)ux*=seed;
ull tmp=0;
for(int i=0;i<l;i++)tmp=tmp*seed+str[i];
mhash[0]=tmp;
for(int i=0;i+l<len;i++){
mhash[i+1]=mhash[i]*seed+str[i+l]-str[i]*ux;
}
//for(int i=0;i<=len-l;i++)
// cout<<hash[i]<<'\n';
int ans=0;
for(int i=0;i<l;i++){
int cnt=0;
map<ull, int>mp;
bool ok=true;
for(int j=i;j<=i+l*(m-1);j+=l){
if(j>len-l){
ok=false;break;
}
mp[mhash[j]]++;
if(mp[mhash[j]]==2)cnt++;
}
if(!ok)break;
if(cnt==0)ans++;
int j=i+l*(m-1);
while(1){
j+=l;
if(j>len-l)break;
mp[mhash[j]]++;
if(mp[mhash[j]]==2)cnt++;
mp[mhash[j-l*m]]--;
if(mp[mhash[j-l*m]]==1)cnt--;
if(cnt==0)ans++;
}
}
printf("%d\n", ans);
}
}