【HDU1232】畅通工程(并查集基础题)

裸敲并查集,很水一次AC

 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cstdio>
 5 #include <cctype>
 6 #include <cmath>
 7 #include <algorithm>
 8 #include <numeric>
 9 #include <string>
10 
11 #pragma comment(linker, "/STACK:102400000,102400000")
12 using namespace std;
13 
14 int cnt = 0;
15 const int V = 1005;
16 int father[V];
17 
18 int getFather (int x) {
19     if (father[x] != x) {
20         father[x] = getFather (father[x]);
21     }
22     return father[x];
23 }
24 
25 void Union (int p, int q) {
26     int x = getFather (p);
27     int y = getFather (q);
28     if (x != y) {
29         father[y] = x;
30         cnt ++;
31     }
32 }
33 
34 int main () {
35     int n, road_n;
36     while (~scanf("%d", &n)) {
37         if (!n) break;
38         scanf("%d", &road_n);//cin >> road_n;
39         cnt = 0;
40         for (int i = 0; i <= n; ++ i) {
41             father[i] = i;
42         }
43 
44         for (int i = 0 ; i < road_n; ++ i) {
45             int x, y; //cin >> x >> y;
46             scanf("%d%d", &x, &y);
47             Union (x, y);
48         }
49         //cout << "cnt :   " << cnt << endl;
50         cout << n - 1 - cnt << endl;
51     }
52     return 0;
53 }

转载于:https://www.cnblogs.com/Destiny-Gem/p/3861514.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值