BNU 4216.修路

在某个景区内有n个景点,它们之间有m条路相连。然而,这m条路可能是不足够的,因为无法把这n个景点都连通起来。
例如当m<n-1的时候,就必定有部分景点被孤立。
所以,现在政府想修建道路,想把这些景点都连通起来。问题是,在现在的基础上,最少要再修建多少条道路呢?

Input
第一行是n,m (1<=n<=1e5,1<=m<=1e6)

接下来就是m行,每行两个1 ~ n范围内的数,表示编号为这两个数的景点之间有一道路相连

Output
输出最少要再修建的道路的条数

Sample Input
5 2
1 2
3 4

Sample Output
2

并查集,在输入的时候不断合并集合,最后要找的就是有多少个景点是孤立的状态,因为每个集合都有个代表元素嘛,弄个vis数组,用来标记代表元素,后面遍历所有点,有多少个不同的代表元素就是有多少个孤立的景点,桥的数目就是景点数-1

#include <iostream>
#include <cstdio>
#include <string.h>
#define N 100005
using namespace std;

long  u[N], rank[N], n, m;

void make()
{
    for(long i = 1; i <= n; i++)
    {
        u[i] = i;
        rank[i] = 1;
    }
}

long find(long x)
{
    if (x != u[x])
        u[x] = find(u[x]);
    return u[x];
}

void unionset(int x, int y)
{
    if ((x = find(x)) == (y = find(y)))
        return;
    if (rank[x] > rank[y])
    {
        u[y] = x;
    }
    else
    {
        u[x] = y;
        if (rank[x] == rank[y])
        {
            rank[y]++;
        }
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("1.txt", "r", stdin);
#endif
    long i, j, a, b, num;
    while(~scanf("%ld%ld", &n, &m))
    {
        num = 0;
        make();
        for(i = 0; i < m; i++)
        {
            scanf("%ld%ld", &a, &b);
            unionset(a, b);
        }
        for (i = 1; i <= n; i++)
        {
            if (i == find(i))
            {
                num++;
            }
        }
        cout << num - 1 << endl;
    }
    return 0;
}

你可能感兴趣的:(并查集)