AW138 rabbit and hare ([template] string hash)

Topics address


The basic idea:

  • hash [i] = hash [i-1] * base + s [i]. (base: a selected prime number, such as 101,171, etc.)
  • Essence: Prefix product.
  • For a range of l ~ r, may be utilized hash [r] -hash [l] * tmp [r-l + 1] acquired (tmp: base product prefix).

Master the skills:

  • Simulation manually.

#include<cstdio>
#include<iostream>
#include<cstring>
#define ull unsigned long long
using namespace std;
const int MAXN=2e6;
string s;
ull hash_[MAXN],tmp[MAXN];
void initHash(){
	int len=s.length();
	ull base=101;
	tmp[0]=1;
	for(int i=1;i<=len;i++){
		hash_[i]=hash_[i-1]*base+s[i-1];
		tmp[i]=tmp[i-1]*base;
	}
}

int main(){
	cin>>s;
	initHash();
	int m;
	scanf("%d",&m);
	for(int i=1;i<=m;i++){
		int l1,r1,l2,r2;
		scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
		ull hash1=hash_[r1]-hash_[l1-1]*tmp[r1-l1+1];
		ull hash2 = hash_ [r2] -hash_
		if(hash1==hash2){
			printf("Yes\n");
		}else printf("No\n");
	}
	return 0;
} 

  

Guess you like

Origin www.cnblogs.com/zbsy-wwx/p/11765348.html