hihoCoder-1066-无间道之并查集

这题的话我们读入可以用cin这样避免混合输入时的错误,虽然慢一点点,但是我们也可以关闭和stdio 的同步,这样就不慢了。
对于主函数来说,查询的时候,如果两个名字都不存在,那么find(0)==find(0),那就会输出yes,所以对于有任意一个为0的情况,我们就输出no。
我们也可以先编号后操作,两种写法都行。

#include <iostream>
#include <string>
#include <map>
using namespace std;
map<string, int> mp;
const int maxn = 200005;
int pre[maxn];

int find(int x)
{
    if (pre[x]==x)
        return x;
    return pre[x] = find(pre[x]);
}

void unions(int a,int b)
{
    int x=find(a);
    int y=find(b);
    if (x!=y)
        pre[x] = y;
}

int main()
{
    int n, op, cnt=1;
    for (int i = 0; i < maxn; i++)
        pre[i] = i;
    cin >> n;
    while (n--) {
        string a, b;
        cin >> op >> a >> b;
        // if (!mp[a])
        //     mp[a] = cnt++;
        // if (!mp[b])
        //     mp[b] = cnt++;
        // if (!op)
        //     unions(mp[a], mp[b]);
        // else if (find(mp[a])==find(mp[b]))
        //     cout << "yes" << endl;
        // else
        //     cout << "no" << endl;
        if (!op) {
            if (!mp[a])
                mp[a]=cnt++;
            if (!mp[b])
                mp[b]=cnt++;
            unions(mp[a], mp[b]);
        }
        else {
            if (mp[a]==0||mp[b]==0) {
                cout << "no" << endl;
                continue;
            }
            if (find(mp[a])==find(mp[b]))
                cout << "yes" << endl;
            else
                cout << "no" << endl;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xyqxyq/p/10366568.html