Hdu1232 畅通工程 【并查集】

http://acm.hdu.edu.cn/showproblem.php?pid=1232

题目大意:有几个集合,问最少需要连几根线才能把这些集合并为一个集合。

N个集合的话就需要N-1条路就行了,简单并查集

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
template <class T> void checkmin(T &t,T x) {if(x < t) t = x;}
template <class T> void checkmax(T &t,T x) {if(x > t) t = x;}
template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;}
template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;}
typedef pair <int,int> PII;
typedef pair <double,double> PDD;
typedef long long ll;
#define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++)
const int N = 1111;
int f[N] , n , m;
bool vis[N];
int find(int x) {
    return x == f[x] ? x : f[x] = find(f[x]);
}
void Union(int x,int y) {
    int a = find(x) , b = find(y);
    f[a] = f[b] = f[x] = f[y] = min(a , b);
}
int main() {
    while(~scanf("%d",&n) && n) {
        scanf("%d",&m);
        for(int i=1;i<=n;i++) f[i] = i , vis[i] = 0;
        while(m--) {
            int x , y;
            scanf("%d%d",&x,&y);
            Union(x ,  y);
        }
        int ans = -1;
        for(int i=1;i<=n;i++) {
            int x = find(i);
            if(!vis[x]) {
                vis[x] = 1;
                ans ++;
            }
        }
        printf("%d\n" , ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/aiiYuu/archive/2013/03/30/2989960.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值