题目传送门:P2256 一中校运会之百米跑 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
知识点:
代码:
// https://www.luogu.com.cn/problem/P2256
// 哈希 + 并查集
#include<bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
const int mod = 10000;//人数范围
const int hhash = 233;// 哈希数
int val[N];//存所处连通块的代表元
//根据名字生成对应的哈希值,映射到哈希表上
int Hash(std::string str) {
int cnt = 0;
for(int i = 0; i < str.length(); i++) {
cnt = (cnt + str[i] * hhash) % mod;
}
return cnt;
}
// 找该数的代表元
int find(int x) {
while(val[x] != x) x = val[x];
return x;
}
// 合并两个连通块
void join(int x, int y) {
int fx = find(x), fy = find(y);
if(fx != fy) val[fx] = fy;
}
int main() {
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; i++) {
string str;
cin >> str;
int x = Hash(str);
val[x] = x;// 每个人单独成一个联通块
}
for(int i = 1; i <= m; i++) {
string str1, str2;
cin >> str1 >> str2;
int x = Hash(str1), y = Hash(str2);
join(x, y); // 合并
}
int k;
cin >> k;
for(int i = 1; i <= k; i++) {
string str1, str2;
cin >> str1 >> str2;
int a = Hash(str1), b = Hash(str2);
a = find(a), b = find(b);//找各自的代表元并比较
if(a == b) cout << "Yes." << '\n';
else cout << "No." << '\n';
}
return 0;
}
还可以优化但这题不用也能过