拉链法
就是链式前向星,或者是单链表
直接用一种方法进行映射,
如果出现重复的值,用链式前向星去存储
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 100010, mod = 100003;
int h[N], e[N], ne[N], idx;
void add(int a){
int l = (a % mod + mod) % mod;
e[idx] = a;
ne[idx] = h[l];
h[l] = idx ++;
}
bool find(int u){
int l = (u % mod + mod) % mod;
for(int i = h[l] ; ~i ; i = ne[i]){
int j = e[i];
if(j == u)
return true;
}
return false;
}
int main(){
int _;
scanf("%d ",&_);
memset(h, -1, sizeof h);
while(_--){
char ch;
int l;
scanf("%c %d ",&ch,&l);
if(ch == 'I') add(l);
else{
int a = find(l);
if(a == 0) puts("No");
else puts("Yes");
}
}
return 0;
}
开放寻址法(开放寻厕法)
从开始的那个点开始往下找 坑位 (拉 * ),如果找到就 拉 * ,
数组得和mod开的一样大,相当于一个队列了
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 200003, mod = 200003;
int e[N];
void add(int u){
int l = (u % mod + mod) % mod;
int s = l;
while(1){
if(e[s]) s ++;
else{
e[s] = u;
break;
}
if(s == N) s = 0;
}
}
bool find(int u){
int l = (u % mod + mod) % mod;
int s = l;
int t = 1;
if(e[s] == u) return true;
s ++;
while(t){
if(e[s]){
if(e[s]!=u) s++;
else
return true;
}
else
return false;
if(s == N) s = 0;
}
}
int main(){
int _;
scanf("%d ",&_);
while(_--){
char ch;
int l;
scanf("%c %d ",&ch,&l);
if(ch == 'I') add(l);
else{
if(find(l) == 0) puts("No");
else puts("Yes");
}
}
return 0;
}
Y总代码
#include <cstring>
#include <iostream>
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;
scanf("%d", &n);
while (n -- )
{
char op[2];
int x;
scanf("%s%d", op, &x);
if (*op == 'I') h[find(x)] = x;
else
{
if (h[find(x)] == null) puts("No");
else puts("Yes");
}
}
return 0;
}
整一个寻找地址的函数,在主函数中进行判断
有点前缀和的意思,
就是说把字符串当成是一种进制,然后把该进制变化为10进制继续比较
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define ull unsigned long long
const int q = 131;
int n, m;
char ch[100010];
ull z[100010];
ull h[100010];
void hanshu(){
h[0] = 1;
for(int i = 1;i <= n;i ++){
z[i] = z[i-1] * q + ch[i] - '0';
h[i] = h[i-1] * q;
}
}
ull find(int x, int y){
return z[y] - z[x - 1] * h[y - x + 1];
}
int main(){
scanf("%d%d",&n,&m);
scanf("%s",ch + 1);
hanshu();
while(m --){
int x1,y1,x2,y2;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(find(x1, y1) == find(x2, y2)) puts("Yes");
else puts("No");
}
return 0;
}