1. 题目来源
链接:P3405 [USACO16DEC]Cities and States S
相关题目:[字符串哈希+模板]字符串哈希
2. 题目解析
字符串哈希的基本应用,重点在数据组织上了。
且本题花里胡哨做法很多,map
当然也是个很好的选择。可以看看题解区大佬的各种做法。
拿出前两位字符组织成一个长度为 4 的字符串,进行字符串哈希映射,在 vector
中依旧模拟开散列,哈希取模值作为下标,哈希值作为字符串唯一标识,记录出现个数。
注意题目要求处于同一洲的两城市并不计算在内。
其实这样的数据组织就是一个 unordered_map
了。
代码:
// https://www.luogu.com.cn/problem/P3405
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
typedef long long LL;
const int N = 5, MOD = 23333;
int n;
char a[N], b[N];
LL res;
vector<pair<int, int> > h[MOD + 5]; // 哈希取模值---原哈希值,出现次数
int get(char a[], char b[]) {
return (a[0] - 'A') * 26 + (a[1] - 'A') * 26 * 26 +
(b[0] - 'A') * 26 * 26 * 26 + (b[1] - 'A') * 26 * 26 * 26 * 26;
}
void insert(int x) {
for (int i = 0; i < h[x % MOD].size(); i ++ ) {
if (h[x % MOD][i].first == x) {
h[x % MOD][i].second ++ ;
break;
}
}
h[x % MOD].push_back(make_pair(x, 1));
}
int find(int x) {
for (int i = 0; i < h[x % MOD].size(); i ++ )
if (h[x % MOD][i].first == x)
return h[x % MOD][i].second;
return 0;
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i ++ ) {
scanf("%s%s", a, b);
if (a[0] == b[0] && a[1] == b[1]) continue; // 相同城市不计算在内
res += find(get(b, a));
insert(get(a, b));
}
printf("%lld\n", res);
return 0;
}