题解 | #畅通工程#

畅通工程

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

#include <iostream>
using namespace std;
int n;
//x为下标
int getFather(int arr[],int x){
    while(arr[x] !=-1){
        x = arr[x];
    }
    return x;
}
void joint(int arr[],int a,int b){
    int aFather = getFather(arr,a);
    int bFather = getFather(arr,b);
    if(aFather == bFather)return;
    arr[aFather] = bFather;
}
int main() {
    int m;//n个城镇,m条路
    while(cin>>n>>m){
        int towns[n+1];//0丢弃,编号1-n
        for(int i =0;i<=n;i++)towns[i]=-1;//都为独立节点
        int a,b;
        while(m--){
            cin>>a>>b;
            joint(towns,a,b);
        }
        int count=-1;
        for(int i=1;i<=n;i++)
            if(towns[i]==-1)count++;
        cout<<count<<endl;
    }
}
// 64 位输出请用 printf("%lld")

并查集的应用

全部评论

相关推荐

01-27 15:41
门头沟学院 Java
想躺平的菜鸡1枚:我项目比你难、学历比你好、还有SCI论文,投java都被拒一大片,现在基本上都要问点agent开发
软件开发投递记录
点赞 评论 收藏
分享
开发转测第二人:没实习的话,两个项目吧,八股也要准备一下,这个时间点有点小晚了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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