BNU - 4216 - 修路(并查集)

来源:互联网 发布:金十数据现货黄金 编辑:程序博客网 时间:2024/05/11 22:15

BNU 4216.修路

Time Limit: 1000msMemory     Limit: 65536KB

在某个景区内有n个景点,它们之间有m条路相连。然而,这m条路可能是不足够的,因为无法把这n个景点都连通起来。

例如当m

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<cstdio>#include<cstring>#include<algorithm>using namespace std;int uset[100010], vis[100010];int find(int x){    if(x != uset[x])        uset[x] = find(uset[x]);    return uset[x];}int main(){    int n, m;    while(scanf("%d %d", &n, &m)!=EOF){        for(int i = 0; i <= n; i++) uset[i] = i;        memset(vis, 0, sizeof(vis));        for(int i = 0; i < m; i++){            int a, b;            scanf("%d %d", &a, &b);            a = find(a);            b = find(b);            if(a != b)                uset[a] = b;        }        int ans = 0;        for(int i = 1; i <= n; i++){            int t = find(i);            if(!vis[t]){                vis[t] = 1;      //标记代表元素                 ans++;            }        }        printf("%d\n", ans-1);    }    return 0;}
0 0
原创粉丝点击