B.DongDong认亲戚

链接:https://ac.nowcoder.com/acm/contest/904/B

题意:

DongDong每年过春节都要回到老家探亲,然而DongDong记性并不好,没法想起谁是谁的亲戚(定义:若A和B是亲戚,B和C是亲戚,那么A和C也是亲戚),她只好求助于会编程的你了。

思路:

并查集模板题。

map记录人。

代码:

#include <bits/stdc++.h>
 
using namespace std;
 
typedef long long LL;
const int MAXN = 2e4 + 10;
const int MOD = 1e9 + 7;
int n, m, k, t;
 
map<string, int> name;
int Fa[MAXN];
 
int GetF(int x)
{
    if (Fa[x] == x)
        return x;
    Fa[x] = GetF(Fa[x]);
    return Fa[x];
}
 
int main()
{
    string s;
    cin >> n >> m;
    for (int i = 1;i <= n;i++)
    {
        Fa[i] = i;
        cin >> s;
        name[s] = i;
    }
    int op;
    string l, r;
    for (int i = 1;i <= n;i++)
    {
        cin >> op >> l >> r;
        if (op == 1)
            Fa[GetF(name[l])] = GetF(name[r]);
        else
        {
            int tl = GetF(name[l]);
            int tr = GetF(name[r]);
            if (tl != tr)
                cout << 0 << endl;
            else
                cout << 1 << endl;
        }
    }
 
    return 0;
}

  

原文地址:https://www.cnblogs.com/YDDDD/p/10989563.html