题解 | #连通图#

连通图

https://www.nowcoder.com/practice/569e89823a5141fe8a11ab7d4da21edf

#include <cstdio>
#include <iostream>
#include <string>

const int MAX=1000;
using namespace std;
int father[MAX];
int height[MAX];

void Initialize(int n){
    for(int i=0;i<n;i++){
        father[i]=i;
        height[i]=0;
    }
    return;
}

int findRoot(int x){
    while(x!=father[x]){
        return findRoot(father[x]);
    }
    return father[x];
}

void Union(int x,int y){
    x= findRoot(x);
    y= findRoot(y);

    if(x!=y){
        if(height[x]< height[y]){
            father[x]=y;
        }else if(height[y]<height[x]){
            father[y]=x;
        }else{
            father[y]=x;
            height[x]++;
        }
    }
    return;
}

int main(){
    int N,M;
    while(scanf("%d",&N)!=EOF){
        Initialize(N);
        scanf("%d",&M);
        while(M--){
            int x,y;
            scanf("%d %d",&x,&y);
            Union(x,y);
        }
        int answer=-1;
        for(int i=0;i<N;i++){
            if(father[i]==i){
                answer++;
            }
        }
        if(answer<=0){
            printf("YES\n");
        }else{
            printf("NO\n");
        }


    }
    return 0;
}

全部评论

相关推荐

路过的周先森:我就喜欢这种无限复活+筛选快的,比那些投进去就没声还占用投递次数的好多了
投递快手等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务