问题来源 : ACWing
https://www.acwing.com/blog/content/277/
C++ 哈希表的详细介绍 : https://blog.csdn.net/duchenlong/article/details/107116015
模拟散列表
拉链法
在散列表的建立中,所使用的方法为拉链法
,每一个可以为哈希键值的位置,底下都是一个单链表,单链表使用一维数组进行模拟。
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
int h[N],e[N],ne[N],idx;
int n;
void insert(const int x) {
int k = (x % N + N) % N;
e[idx] = x;
ne[idx] = h[k];
h[k] = idx++;
}
bool query(const int x) {
int k = (x % N + N) % N;
for(int u = h[k]; ~u; u = ne[u]) {
if(e[u] == x) return true;
}
return false;
}
int main() {
cin >> n;
memset(h,-1,sizeof h);
while(n --) {
char oper;
int x;
cin >> oper >> x;
if(oper == 'I') insert(x);
else if(oper == 'Q') {
if(query(x)) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
return 0;
}
开放地址寻址法
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5 + 3, inf = 0x3f3f3f3f;
int h[N];
int n;
void insert(const int x) {
int k = (x % N + N) % N;
while(h[k] != inf) {
k++;
if(k == N) k = 0;
}
h[k] = x;
}
bool query(const int x) {
int k = (x % N + N) % N;
while(h[k] != inf && h[k] != x) {
k++;
if(k == N) k = 0;
}
return h[k] == x;
}
int main() {
cin >> n;
memset(h,0x3f,sizeof h);
while(n --) {
char oper;
int x;
cin >> oper >> x;
if(oper == 'I') insert(x);
else if(oper == 'Q') {
if(query(x)) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
return 0;
}
字符串哈希
全称字符串前缀哈希法
,通过把字符串变成一个p进制数字(哈希值),实现不同的字符串映射到不同的数字。
注意点:
- 任意字符不可以映射成0,否则会出现不同的字符串都映射成0的情况,比如
A,AA,AAA
皆为0 - 冲突问题:通过巧妙设置P (
131
或13331
,经验值) ,Q(2^64)
的值,一般可以理解为不产生冲突。
问题是比较不同区间的子串是否相同,就转化为对应的哈希值是否相同。
求一个字符串的哈希值就相当于求前缀和,求一个字符串的子串哈希值就相当于求部分和。
#include <iostream>
#include <string>
using namespace std;
typedef unsigned long long ULL;
const int N = 1e5 + 10, P = 131;
char s[N];
ULL h[N],p[N];
int n,m;
ULL get(const int l,const int r) {
return h[r] - h[l - 1] * p[r - l + 1];
}
int main() {
scanf("%d%d%s",&n,&m,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];
}
int l1,r1,l2,r2;
while(m --) {
scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
if(get(l1,r1) == get(l2,r2)) printf("Yes\n");
else printf("No\n");
}
return 0;
}