hdu 4821 String(字符串hash+map)

首先用字符串hash把每一个长度为L的字串的hash值预处理出来。

然后用一个map来记录当前处理的长度为L*M的这一段中中每个子串出现过几次。

一共要把这个串扫n次,这个n是开始的位置,比如abcabcbcaabc这个串,就把它按 abc abc bca abc;a bca bcb caa bc; ab cab cbc aab c;这三种方法分组,其中n取值分别为0,1,2,这样虽然看起来是扫了n次整个串,但是实际上每个子串一共只被扫过一次,整体还是O(n)的

每次扫的时候用dist记录当前这个段有多少不同的子串,a从左向右移动,每次增加L,当扫a到a-L这一段时,先把vis中a-L-1这个位置的hash值出现次数减1,如果到零了,就把dist-1(没有这个串了),再把a这个位置的hash值出现次数+1,如果等于1,就把dist+1。

如果dist==M 总答案就加1


代码:

#include <iostream>
#include <map>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define LL long long
#define maxn 100005
const int seed=10000007;
map <unsigned LL,int> vis;
unsigned LL H[maxn];
unsigned LL xp[maxn];
char s[maxn];
int L,M;
int MaxL;
unsigned LL Hash[maxn];
void init(){
	H[MaxL]=0;
	for(int i=MaxL-1;i>=0;i--) H[i]=H[i+1]*seed+(s[i]- 'a');
	xp[0]=1;
	for(int i=1;i<=MaxL;i++){
		xp[i]=xp[i-1]*seed;
	}
	for(int i=0;i<MaxL-M+1;i++){
		Hash[i]=H[i]-H[i+L]*xp[L];
		vis[Hash[i]]=0;
	}
}

int solve(){
	int res=0;
	int i,j;
	for(i=0;i<min(MaxL-L*M+1,L);i++){
	//for(i=0;i<2;i++){
		vis.clear();
		int dist=0;
		for(j=i;j<L*M+i;j+=L){
			vis[Hash[j]]++;
			if(vis[Hash[j]]==1) dist++;
		}
		//cout<<i<<' '<<dist<<endl;
		if(dist==M) res++;
		for(;j<=MaxL-L;j+=L){
			vis[Hash[j-M*L]]--;
			if(vis[Hash[j-M*L]]==0) dist--;
			vis[Hash[j]]++;
			if(vis[Hash[j]]==1) dist++;
			if(dist==M) res++;
			//cout<<i<<' '<<dist<<endl;
		}
	}
	return res;
}

int main(){
	while(~scanf("%d%d",&M,&L)){
		scanf("%s",s);
		MaxL=strlen(s);
		init();
		printf("%d\n",solve());
	}
	return 0;
}
	


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值