牛客小白月赛77 D-小Why的密码锁 双哈希做法

这道题没卡自然溢出的哈希,但mod为1e9的哈希被卡了。

双哈希只需把单哈希做法中的lst和ans转换成 <PII, int>类型的即可。

#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'

using namespace std;

typedef pair<int, int> PII;
typedef long long ll;

const int N = 1000010, mod1 = 1e9 + 7, mod2 = 1e9 + 11;
const int P1 = 131, P2 = 13331;

int n, m, k;
char s[N];
ll p1[N], p2[N], h1[N], h2[N];

map<PII, int> lst, ans;

ll get1(int l, int r)
{
	if(l > r)swap(l, r);
	return (h1[r] - h1[l - 1] * p1[r - l + 1] % mod1 + mod1) % mod1;
}

ll get2(int l, int r)
{
	if(l > r)swap(l, r);
	return (h2[r] - h2[l - 1] * p2[r - l + 1] % mod2 + mod2) % mod2;
}

int main()
{
	IOS
	p1[0] = p2[0] = 1;
	cin >> n >> m >> k;
	cin >> s + 1;
	
	for(int i = 1; i <= n; i ++)
	{
		h1[i] = (h1[i - 1] * P1 + s[i]) % mod1;
		h2[i] = (h2[i - 1] * P2 + s[i]) % mod2;
		
		p1[i] = p1[i - 1] * P1 % mod1;
		p2[i] = p2[i - 1] * P2 % mod2;
	}
	
    for(int i = 1; i <= n - m + 1; i ++)
	{
		int hash1 = get1(i, i + m - 1), hash2 = get2(i, i + m - 1);
		
        if(lst[{hash1, hash2}] < i)
        {
            lst[{hash1, hash2}] =i + m - 1;
            ans[{hash1, hash2}] ++;
        }
	}
	
	int res = 0;
	for(auto item : ans)
	{
		if(item.second == k)res ++; 
	}
	cout << res;
	
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值