hdu1232_畅通工程
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1232
题意:给定城镇数量n,给出m条道路,问你还需要修几条路才能把所有的城镇连接起来。
只要两个城镇之间有通路即可,不一定是直接连接。
思路:可以使用并查集来存储现有的路,然后查找这些分为多少块,统计出有多少块之
后,将这些块连接起来那么这写城镇就是连通的。
1 /* 2 * hdu1232_畅通工程.cpp 3 * Created on: 2013年8月26日 4 * Author: pirate 5 */ 6 #include <set> 7 #include <map> 8 #include <list> 9 #include <deque> 10 #include <queue> 11 #include <cmath> 12 #include <bitset> 13 #include <vector> 14 #include <cstdio> 15 #include <string> 16 #include <cstring> 17 #include <fstream> 18 #include <cstdlib> 19 #include <iostream> 20 #include <algorithm> 21 using namespace std; 22 #define N 2000 23 #define I64 __int64 24 #define LL long long 25 #define PI acos(-1.0) 26 #define L(a) ((a)<<1) 27 #define R(a) ((a)<<1+1) 28 #define sqr(a) ((a)*(a)) 29 #define MID(a,b) ((a)+(b))/2 30 #define ABS(a) (a)>0?(a):(-a) 31 #define MAX(a,b) ((a)>(b)?(a):(b)) 32 #define MIN(a,b) ((a)<(b)?(a):(b)) 33 #define INIT(a,b) memset(a,b,sizeof(a)) 34 35 int fa[N]; 36 int n,m; 37 void init(){ 38 for(int i = 0;i < N;i ++) 39 fa[i] = i; 40 } 41 int Find(int x){ 42 if(x == fa[x]) 43 return x; 44 else 45 return Find(fa[x]); 46 } 47 void Unit(int x,int y){ 48 int xx = Find(x); 49 int yy = Find(y); 50 if(xx != yy){ 51 fa[xx] = yy; 52 } 53 } 54 int main(){ 55 while(scanf("%d",&n)!=EOF){ 56 if(n == 0) 57 break; 58 scanf("%d",&m); 59 init();//初始化 60 for(int i = 0;i < m;i ++){ 61 int x,y; 62 scanf("%d%d",&x,&y); 63 Unit(x,y);//将节点加到树中 64 } 65 int cnt = 0; 66 for(int i = 1;i <= n;i ++){//统计有多少颗树 67 if(fa[i] == i) 68 cnt += 1; 69 } 70 printf("%d\n",cnt-1); 71 } 72 return 0; 73 }

浙公网安备 33010602011771号