String hash ---------------------------------------- template

Given a string of length n, and then given m queries, each query contains four integers l1, r1, l2, r2, please judge the two intervals [l1, r1] and [l2, r2] Whether the contained string substrings are identical.

The string contains only uppercase and lowercase English letters and numbers.

Input format The
first line contains integers n and m, indicating the string length and the number of queries.

The second line contains a string of length n, which contains only uppercase and lowercase English letters and numbers.

The next m lines, each line contains four integers l1, r1, l2, r2, representing the two intervals involved in a query.

Note that the position of the character string starts from 1.

Output format
For each query, a result is output. If the two character string substrings are identical, output "Yes", otherwise output "No".

Each result is on a line.

Data range
1≤n, m≤105
Input sample:
8 3
aabbaabb
1 3 5 7
1 3 6 8
1 2 1 2
Output sample:
Yes
No
Yes

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+1000;
typedef unsigned long long ull;
int n,k;
ull P=131;
ull h[N],p[N];
char s[N];
ull get(ull l,ull r)
{
	return h[r]-h[l-1]*p[r-l+1]; 
}
int main()
{
	cin>>n>>k;
	cin>>(s+1);
	p[0]=1;
	for(int i=1;i<=n;i++)
	{
		p[i]=p[i-1]*P;
		h[i]=h[i-1]*P+s[i];
	}
	while(k--)
	{
		int l1,r1,l2,r2;
		cin>>l1>>r1>>l2>>r2;
		if(get(l1,r1)==get(l2,r2)) cout<<"Yes"<<endl;
		else cout<<"No"<<endl;
	}
}

Published 572 original articles · praised 14 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/105452497