P3370. 字符串哈希

考点

  • 哈希函数

题解

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
#include <bits/stdc++.h>
using namespace std;
const int LEN = 23333, P = 131;
string s;
vector<string> hsh[LEN];
int ans;

void f()
{
int h = 0;
for (int i = 0; i < (int)s.length(); ++i)
h = (1ll * P * h + s[i]) % LEN;
for (int i = 0; i < hsh[h].size(); ++i)
{
if (hsh[h][i] == s)
return;
}
hsh[h].emplace_back(s);
++ans;
}

int main()
{
int n;
cin >> n;
while (n--)
{
cin >> s;
f();
}
cout << ans;
return 0;
}

思路

经典的拉链法处理哈希碰撞

拉链法是在每个存放数据的地方开一个链表/数组

如果有多个键值索引到同一个地方,把它们都放到那个位置的链表/数组中

查询的时候需要把对应位置的链表/数组整个扫一遍,对其中的每个数据比较其键值与查询的键值是否一致