浅谈·哈希
hash
如何存储一些数字/字符。
数字:通过取模存入表中。
字符:通过一些运算和取模存入表中。
处理冲突:
取模冲突了就把数字或者字符存到那一个取模下面。
OK.
P1955 代码。
#include <bits/stdc++.h>
using namespace std;
int base = 128;
int MOD = 482347;
vector<string> k[482350]; // key值
int ans = 0;
int P3370_Insert_Find(string s) {
int key = 1; // 获取 key 值。
for (int i = 0; i < s.size(); i++) {
// 如果是十进制就相当于 x = x * 10 + m.(0 <= m <= 9).
key = (key * base + int(s[i])) % MOD;
}
//cout << key << "\n";
for (int i = 0; i < k[key].size(); i++) {
if (k[key][i] == s) {
return 0;
}
}
k[key].push_back(s);
return 1;
}
int n;
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
ans = ans + P3370_Insert_Find(s);
}
cout << ans << "\n";
return 0;
}