码迷,mamicode.com
首页 > 其他好文 > 详细

hdu1232---畅通工程

时间:2018-08-01 20:49:18      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:name   改变   src   else   lse   close   mes   spl   root   

tips:

  1.并查集裸题,用isroot数组记录有几个根节点。

  3.改变isroot数组类型可以统计一个集合中元素的个数。----isroot[finddad(i)]++;

  2.hdu1272--isroot数组出bug了。

技术分享图片
#include<bits/stdc++.h>
using namespace std;
const int M=1010;
int father[M];
int isroot[M];
int n,m;
int a,b;
void init(){
    for(int i=1;i<=n;i++){
        father[i]=i;
        isroot[i]=0;
    }

}
int finddad(int x){
    if(x == father[x])  return x;
    else return father[x]=finddad(father[x]);
}
void unionn (int x, int y){
    int fx=finddad(father[x]);
    int fy=finddad(father[y]);
    if(fx != fy) father[fx]=fy;
}
int main(){
    while(cin>>n>>m){
        if(n == 0) break;
        if(m==0)  {
            cout<<n-1<<endl;
            continue;
        }
        init();
        for(int i=0;i<m;i++){
            cin>>a>>b;
            unionn(a,b);

        }
        for(int i=1;i<=n;i++){
            int x=finddad(i);
            isroot[x]=1;
        }
        int ans=0;
        for(int i=1;i<=n;i++){
            ans+=isroot[i];
        }
        cout<<ans-1<<endl;

    }
    return 0;
}
View Code

 

hdu1232---畅通工程

标签:name   改变   src   else   lse   close   mes   spl   root   

原文地址:https://www.cnblogs.com/SUMaywlx/p/9403503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!