【哈希表】AcWing840. 模拟散列表 —— 哈希入门(拉链法与开放寻址法)
AcWing840. 模拟散列表

题解
哈希函数:将题目输入的数映入成0~10^5范围的下标存入数组。
哈希取模的数最好是质数,这样冲突的概率最小(数学上存在证明,感兴趣可去搜)
拉链法

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 100003;
int h[N], ne[N], v[N], idx;
void insert(int x)
{
int k = (x % N + N) % N;
ne[idx] = h[k];
h[k] = idx;
v[idx ++] = x;
}
bool find(int x)
{
int k = (x % N + N) % N;
for(int i = h[k]; ~i; i = ne[i])
if(v[i] == x)
return true;
return false;
}
int main()
{
memset(h, -1, sizeof(h));
int n, x;
char op[5];
scanf("%d",&n);
while(n -- )
{
scanf("%s%d",op,&x);
if(!strcmp("I",op)) insert(x);
else{
if(find(x)) printf("Yes\n");
else printf("No\n");
}
}
return 0;
}
开放寻址法
数组空间需要开2~3倍,其思想就是发生哈希冲突时,往后走,找到第一个为空存入
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 200003, null = 0x3f3f3f3f;
int h[N];
int find(int x)
{
int t = (x % N + N) % N;
while(h[t] != null && h[t] != x)
{
t ++ ;
if(t == N) t = 0;
}
return t;
}
int main()
{
memset(h, 0x3f, sizeof(h));
int n, x;
char op[5];
scanf("%d",&n);
while(n -- )
{
scanf("%s%d",op,&x);
if(!strcmp("I",op)) h[find(x)] = x;
else{
if(h[find(x)] == x) printf("Yes\n");
else printf("No\n");
}
}
return 0;
}

浙公网安备 33010602011771号