字符串哈希
#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<map>
#include<vector>
#include<set>
#include<stack>
#include<algorithm>
#include<vector>
#include<utility>
#include<deque>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define endl '\n'
#define eps 1e-8
#define mem(n,a) memset(n,a,sizeof(n))
#define rep(i,be,en) for(int i=be;i<=en;++i)
#define pre(i,be,en) for(int i=en;i>=be;--i)
inline int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
inline int lowbit(int x) { return x & -x; }
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
const int N = 1e5 + 10, P = 131;
ull h[N], p[N];
int n, m;
char str[N];
ull get(int l, int r) {
return h[r] - h[l - 1] * p[r - l + 1];
}
int main() {
scanf("%d%d%s", &n, &m, str + 1);
p[0] = 1;
for (int i = 1;i <= n;++i) {
p[i] = p[i - 1] * P;
h[i] = h[i - 1] * P + str[i];
}
while (m--) {
int l1, r1, l2, r2;
scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
if (get(l1, r1) == get(l2, r2))puts("Yes");
else puts("No");
}
return 0;
}
普通哈希
开放寻址法
#include<iostream>
#include<cstring>
using namespace std;
const int N = 2e5+3,null = 0x3f3f3f3f;
int h[N];
int n;
int find(int x){
int k = (x % N + N) % N;
while(h[k] != null && h[k] != x){
++k;
if(k == N)k =0;
}
return k;
}
int main(){
scanf("%d",&n);
memset(h,0x3f,sizeof h);
while(n--){
char op;
int x;
cin >> op >> x;
int k = find(x);
if(op == 'I')h[k] = x;
else {
if(h[k] != x)puts("No");
else puts("Yes");
}
}
return 0;
}
拉链法