hihoCoder week14 无间道之并查集

并查集的基本使用

 

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;

int n, fa[N];
int cnt, tot;
map<string ,int> mp;
string s[N], s1, s2;
void init() {
    for(int i=0; i<N; i++) 
        fa[i] = i;
}

int fi(int x) {
    return fa[x] == x ? x : fa[x] = fi(fa[x]);
}
int getId(string str)
{
    if(mp[str]) {
        return mp[str];
    }
    mp[str] = (++cnt);
    s[cnt] = str;
    return cnt;
}
void join(int u,int v) 
{
    int fu = fi(u);
    int fv = fi(v);
    if(fu != fv) {
        fa[fu] = fv;
    }
}

bool same(int u,int v) 
{
    return fi(u) == fi(v);
}
int main()
{
    freopen("in.txt","r",stdin);
    init();
    scanf("%d", &n);
    while(n--) {
        int op;
        cin >> op >> s1 >> s2;
        int u = getId(s1);
        int v = getId(s2);
        if(!op) {
            join(u,v);
        }else {
            if(same(u,v)) {
                puts("yes");
            }
            else {
                puts("no");
            }
        }
    }
    return 0;
}

 

posted @ 2018-11-23 14:48  Draymonder  阅读(145)  评论(0编辑  收藏  举报