You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int MOD = 23333; //需要模的常数,一般为质数
int n;
string a, B;
vector<PII> linker[MOD + 10];
int ans; //极限值是20000*20000=400000000,是不会爆int的,这个分析很棒~
//算出两个字符串拼在一起的Hash值
int getHash(string a, string b) {
//扩展阅读 秦九韶算法
//https://haokan.baidu.com/v?pd=wisenatural&vid=14006885485484083472
//26进制的意思当然这个26也可以是大于26的任意值
return a[0] - 'A' + (a[1] - 'A') * 26 + (b[0] - 'A') * 26 * 26 + (b[1] - 'A') * 26 * 26 * 26;
}
//插入到链表
void insert(int x) {
for (int i = 0; i < linker[x % MOD].size(); i++)
if (linker[x % MOD][i].first == x) {
linker[x % MOD][i].second++;
return; //此处,书上的代码有错误
}
linker[x % MOD].push_back({x, 1});
}
//查询Hash值等于x的个数是多少
int find(int x) {
for (int i = 0; i < linker[x % MOD].size(); i++)
if (linker[x % MOD][i].first == x)
return linker[x % MOD][i].second;
return 0;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a >> b;
//如果反过来掉过去都一样,就是自己和自己,不是特殊的一对,只有不一样的才可能是特殊的一对
if (a.substr(0, 2) != b.substr(0, 2)) {
//将a和b的hash计算出来并存入Hash表中
insert(getHash(a, b));//如果不存在则创建值为1如果存在则值++
//计算一下b,a的Hash值是多少查找一下b,a的Hash值个数累加
ans += find(getHash(b, a));
}
}
//输出结果
cout << ans << endl;
return 0;
}