题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4821
题目大意:给你M,L两个字母,问你给定字串里不含M个长度为L的两两相同的子串有多少个?
哈希+枚举
我就是不会枚举这样的,这次涨姿势了。
每次枚举起点,然后就能枚举全部的。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <set>
using namespace std;
typedef unsigned long long ull; const ull B = **+;
int M,L;
char s[];
ull h[];
ull base[];
ull tt[]; int main(){
base[] = ;
for(int i=;i<;i++) base[i] = base[i-]*B;
while(scanf("%d%d",&M,&L)!=EOF){
memset(h,,sizeof(h));
scanf("%s",s);
int len = strlen(s);
for(int i=;i<len;i++){
if( i== ) h[i] = s[i];
else h[i] = h[i-]*B + s[i];
}
int ans = ;
// printf("len = %d\n",len);
for(int i=;i<L;i++){ // 枚举全部起点
// puts("*******************");
int cnt = ;
map<ull,int> H;
for(int j=i;j+L<=len;j+=L){ // 枚举每段
tt[cnt++] = h[j+L-] - (j==?:(h[j-]*base[L]));
// printf("%d => %llu\n",j,tt[cnt-1]);
}
// printf("cnt=%d\n",cnt);
// 迟取法取每段然后数数,注意这里的j<min(cnt,M)
for(int j=;j<min(cnt,M);j++){
// printf("******%llu\n",H[tt[j]]);
H[tt[j]]++;
}
if( H.size()==M ){
ans++;
// printf("%d==%d\n",H.size(),M);
}
for(int j=M;j<cnt;j++){
H[tt[j-M]]--;
if( H[tt[j-M]]== ) H.erase(tt[j-M]);
H[tt[j]]++;
if( H.size()==M ){
ans++;
// printf("%d==%d\n",H.size(),M);
}
}
}
printf("%d\n",ans);
}
return ;
}