hihoCoder 1066 无间道之并查集



我的:

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

int sum;
int pa[100010];
string s[100010];

int findset(int x){
    if(x == pa[x])
        return pa[x];
    else
        return pa[x] = findset(pa[x]);
}

int find_num(string str){
    for(int i = 0; i < sum; i++){
        if(s[i] == str)
            return i;
    }
    s[sum++] = str;
    return sum-1;
}

int main(){
    int n;
    while(scanf("%d",&n) != EOF){
        int l = 2 * n;
        for(int i = 0; i <= l; i++)
            pa[i] = i;
        string str1,str2;
        sum = 0;
        int op,a,b;
        for(int i = 0; i < n; i++){
            cin>>op>>str1>>str2;
            a = find_num(str1);
            b = find_num(str2);
            a = findset(a);
            b = findset(b);
            if(op == 0){
                if(a != b)
                    pa[a] = b;
            }
            else{
                if(a == b)
                    printf("yes\n");
                else
                    printf("no\n");
            }
        }
    }
    return 0;
}


大牛的:

#include <iostream>
#include <cstdio>
#include <string>
#include <map>
using namespace std;

int sum;
int pa[200010];
string s[200010];
map<string,int> m;

int findset(int x){
    if(x != pa[x])
        pa[x] = findset(pa[x]);
    return pa[x];
}

int main(){
    int n;
    while(scanf("%d",&n) != EOF){
        string str1,str2;
        int op,a,b;
        sum = 0;
        map<string,int>:: iterator it;
        for(int i = 0; i < n; i++){
            cin>>op>>str1>>str2;
            it = m.find(str1);
            if(it == m.end()){
                a = sum;
                pa[sum] = sum;
                m.insert(pair<string,int>(str1,sum++));
            }
            else
                a = it->second;
            it = m.find(str2);
            if(it == m.end()){
                b = sum;
                pa[sum] = sum;
                m.insert(pair<string,int>(str2,sum++));
            }
            else
                b = it->second;
            a = findset(a);
            b = findset(b);
            if(op == 0){
                if(a != b)
                    pa[a] = b;
            }
            else{
                if(a == b)
                    printf("yes\n");
                else
                    printf("no\n");
            }
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值