nssl1211-好文章【字符串hash,map】

版权声明:原创,未经作者允许禁止转载 https://blog.csdn.net/Mr_wuyongcong/article/details/83213085

正题


题目大意

求长度为n个一个字符串长度为m不同的子串个数


解题思路

用字符串hash判断字符串是否相同,然后时间复杂度 O ( n 2 ) O(n^2) ,然后我们因为自然溢出所以不能开桶,那就开map。然后就会愉快的被卡,所以再加一个自定义模数。


code

#pragma GCC optimize(2)
#include<cstdio>
#include<algorithm>
#include<map>
#define ull long long
#define p 13331
#define p2 131
#define YMW 1000007
#define N 200010
using namespace std;
int n,m,ans;
ull pow[N],h[N],h2[N],pow2[N];
char s[N];
map<pair<ull,ull>,bool> ok;
ull ask(int l,int r)//循环区间
{
	return (h[r]-h[l-1]*pow[r-l+1]%YMW+YMW)%YMW;
}
ull ask2(int l,int r)//循环区间
{
	return (h2[r]-h2[l-1]*pow2[r-l+1]%YMW+YMW)%YMW;
}
int main()
{
	scanf("%d%d",&n,&m);
	scanf("%s",s+1);
	pow[0]=pow2[0]=1;
	for(int i=1;i<=n;i++)
	{
		pow[i]=(pow[i-1]*p)%YMW;
		pow2[i]=(pow2[i-1]*p2)%YMW;
		h[i]=(h[i-1]*p%YMW+s[i]-'a'+1)%YMW;//hash值1
		h2[i]=(h2[i-1]*p2%YMW+s[i]-'a'+1)%YMW;//hash值2
	}
	for(int i=m;i<=n;i++)
	{
		ull k,k2;
		if(!ok[make_pair(k=ask(i-m+1,i),k2=ask2(i-m+1,i))])
		{
			ok[make_pair(k,k2)]=true;//标记
			ans++;//猩的子串
		}
	}
	printf("%d",ans);
}

猜你喜欢

转载自blog.csdn.net/Mr_wuyongcong/article/details/83213085