题解 | 畅通工程

畅通工程

https://www.nowcoder.com/practice/4878e6c6a24e443aac5211d194cf3913

#include <iostream>
#include <vector>
using namespace std;

vector<int> father(1010);
int setCount;
void Init(int n){
    for(int i=0;i<n;i++){
        father[i] = i;
    }
}

int findRoot(int cur){
    if(cur==father[cur]){
        return cur;
    }else{
        father[cur] = findRoot(father[cur]);
        return father[cur];
    }
}

void unionSet(int c1,int c2){
    int root1 = findRoot(c1);
    int root2 = findRoot(c2);
    if(root1!=root2){
        setCount--;
    }
    father[root1] = root2;
}

int main() {
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        if(n==0) break;
        Init(n+1);
        setCount = n;
        for(int i=0;i<m;i++){
            int a,b;
            scanf("%d%d",&a,&b);
            unionSet(a,b);
        }
        printf("%d\n",setCount-1);
    }
}


// 64 位输出请用 printf("%lld")

全部评论

相关推荐

不愿透露姓名的神秘牛友
03-20 12:46
瘦嘟嘟右卫门:百度文库网盘的暑期也没约面吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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