AcWing 841. 字符串哈希(字符串Hash)

Posted MangataTS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AcWing 841. 字符串哈希(字符串Hash)相关的知识,希望对你有一定的参考价值。

题目连接

https://www.acwing.com/problem/content/843/

思路

我们用一个数组a记录改字符串的前缀hash值,然后和前缀和类似的方法,不过注意的是,我们在计算区间hash值的时候需要对位数较低的数进行移位操作,也就是给a[l-1]乘上一个 p r − l + 1 p^r-l+1 prl+1,然后再和a[r]做运算

代码

#include<bits/stdc++.h>
using namespace std;
//----------------自定义部分----------------
#define ll long long
#define ull unsigned long long
#define mod 1000000007
#define endl "\\n"
#define PII pair<int,int>

int dx[4]=0,-1,0,1,dy[4]=-1,0,1,0;

ll ksm(ll a,ll b) 
	ll ans = 1;
	for(;b;b>>=1LL) 
		if(b & 1) ans = ans * a % mod;
		a = a * a % mod;
	
	return ans;


ll lowbit(ll x)return -x & x;

const int N = 2e6+10,P = 1331;
//----------------自定义部分----------------
ull n,m,q,a[N],p[N];

ull get(int l,int r)
	return a[r] - a[l-1] * p[r-l+1];


int main()

	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	std::cout.tie(nullptr);
	string s;
	cin>>n>>m;
	cin>>s;
	p[0] = 1;
	for(int i = 1;i <= n; ++i) 
		a[i] = a[i-1] * P + s[i-1];
		p[i] = p[i-1] * P;
	
	int l1,r1,l2,r2;
	while(m--) 
		cin>>l1>>r1>>l2>>r2;
		if(get(l1,r1) == get(l2,r2)) cout<<"Yes"<<endl;
		else cout<<"No"<<endl;
	
	
	
	return 0;

以上是关于AcWing 841. 字符串哈希(字符串Hash)的主要内容,如果未能解决你的问题,请参考以下文章

字符串哈希

Acwing Arithmetic Learning:数据结构

841. 字符串哈希

AcWing 139 回文子串的最大长度(二分,hash ver.)

AcWing:138. 兔子与兔子(Hash)

字符串哈希