哈希

哈希表的插入与查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cstring>
using namespace std;

const int N=2e5+3;
const int INF=0x3f3f3f3f;

int h[N];

int find(int x)
{
int k=(x%N+N)%N;
while(h[k]!=INF && h[k]!=x)
{
k++;
if(k==N) k=0;
}
return k;
}
int main()
{
memset(h,0x3f,sizeof h);
int n;
cin>>n;
for(int i=0;i<n;i++)
{
char op;
int x;
cin>>op>>x;
if(op=='I')
{
int k=find(x);
h[k]=x;
}
else
{
int k=find(x);
if(h[k]==INF) cout<<"No"<<endl;
else cout<<"Yes"<<endl;
}
}
}

字符串哈希

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <cstring>
using namespace std;

typedef unsigned long long ULL;//P = 131|13331 Q=2^64,在99%的情况下不会出现冲突
const int N=1e5+10;
int P=131;//p取131|13331
ULL p[N],h[N];

ULL get(int l,int r)
{
return h[r]-h[l-1]*p[r-l+1];
}

int main()
{
int n,m;
cin>>n>>m;

char s[N];
cin>>s+1;
p[0]=1;
h[0]=0;
for(int i=1;i<=n;i++)
{
p[i]=p[i-1]*P;
h[i]=h[i-1]*P+s[i];
}
while(m--)
{
int l1,r1,l2,r2;
cin>>l1>>r1>>l2>>r2;
if(get(l1,r1)==get(l2,r2)) puts("Yes");
else puts("No");
}
}