P2256 一中校运会之百米跑

题目传送门:P2256 一中校运会之百米跑 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

知识点:

        并查集:【算法与数据结构】—— 并查集-CSDN博客

代码:

// 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;
}

还可以优化但这题不用也能过

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值