TAG
-
算法
?
【
S
T
L
、进制哈希】
算法 - 【STL、进制哈希】
算法?【STL、进制哈希】
时间复杂度
-
O
(
?
)
O(\ast)
O(?)
// – STL – //
set
//
#include <bits/stdc++.h>
using namespace std;
// #define int long long
void solve() {
set<string> st;
int n;
scanf("%d", &n);
while (n--) {
string ai;
cin >> ai;
st.insert(ai);
}
printf("%d\n", st.size());
}
signed main() {
int t = 1;
// scanf("%d", &t);
while (t--) solve();
return 0;
}
map
// map
#include <bits/stdc++.h>
using namespace std;
// #define int long long
void solve() {
map<string, int> mp;
int n;
scanf("%d", &n);
while (n--) {
string ai;
cin >> ai;
mp[ai]++;
}
printf("%d\n", mp.size());
}
signed main() {
int t = 1;
// scanf("%d", &t);
while (t--) solve();
return 0;
}
自然溢出
// 自然溢出
#include <bits/stdc++.h>
using namespace std;
#define int unsigned long long
const int base = 131; // (int)'z' = 122 < 131
const int N = 10005;
int mp[N];
int f_hash(string s) {
int ans = 0;
for (int i = 0; i < s.size(); i++) {
ans = ans * base + s[i];
}
return ans;
}
void solve() {
int n;
scanf("%llu", &n);
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
mp[i] = f_hash(s);
}
sort(mp + 1, mp + n + 1);
int ans = 1;
for (int i = 2; i <= n; i++) ans += (mp[i] != mp[i - 1]);
printf("%llu\n", ans);
}
signed main() {
int t = 1;
// scanf("%llu", &t);
while (t--) solve();
return 0;
}
单 mod
// 单 mod
#include <bits/stdc++.h>
using namespace std;
#define int unsigned long long
// const
const int base = 131, mod = 1e9 + 7;
const int N = 10005;
int mp[N];
int f_hash(string s) {
int ans = 0;
for (int i = 0; i < s.size(); i++) {
ans = (ans * base + s[i]) % mod;
}
return ans;
}
void solve() {
int n;
scanf("%llu", &n);
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
mp[i] = f_hash(s);
}
sort(mp + 1, mp + n + 1);
int ans = 1;
for (int i = 2; i <= n; i++) ans += (mp[i] != mp[i - 1]);
printf("%llu\n", ans);
}
signed main() {
int t = 1;
// scanf("%llu", &t);
while (t--) solve();
return 0;
}
双 mod
// 双 mod
#include <bits/stdc++.h>
using namespace std;
#define int unsigned long long
const int base = 131, mod1 = 1e9 + 7, mod2 = 1e9 + 9;
const int N = 10005;
struct A {
int h1, h2;
} mp[N];
A f_hash(string s) {
int ans1 = 0, ans2 = 0;
for (int i = 0; i < s.size(); i++) {
ans1 = (ans1 * base + s[i]) % mod1;
ans2 = (ans2 * base + s[i]) % mod2;
}
return (A){ans1, ans2};
}
bool cmp(const A& x, const A& y) {
return x.h1 == y.h1 ? x.h2 < y.h2 : x.h1 < y.h1;
}
void solve() {
int n;
scanf("%llu", &n);
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
mp[i] = f_hash(s);
}
sort(mp + 1, mp + n + 1, cmp);
int ans = 1;
for (int i = 2; i <= n; i++) ans += !(mp[i].h1 == mp[i - 1].h1 && mp[i].h2 == mp[i - 1].h2);
printf("%llu\n", ans);
}
signed main() {
int t = 1;
// scanf("%llu", &t);
while (t--) solve();
return 0;
}
实现细节
base
- 131
13331
mod
- 1e9 + 7
1e9 + 9
19 个 1
ios::sync_with_stdio(false); cin.tie(nullptr);
参考示意图
参考链接
作者 | 乐意奥AI