1 #include<iostream> 2 #include<stdio.h> 3 #include<string.h> 4 #include<stdlib.h> 5 #include<math.h> 6 #include<algorithm> 7 #define LL long long 8 #define mod 1e9 + 7 9 const int M = 1005; 10 11 using namespace std; 12 13 struct node{ 14 int x; 15 int y; 16 }a[M * M >> 1]; 17 18 int cun[M]; 19 20 int find(int x) 21 { 22 return cun[x] == x ? x : cun[x] = find(cun[x]); 23 } 24 25 void shu(int x, int y) 26 { 27 int p = find(x); 28 int q = find(y); 29 cun[p] = q; 30 } 31 32 int main() 33 { 34 int n, m; 35 while( cin >> n ) 36 { 37 if(n == 0) 38 break; 39 cin >> m; 40 for(int i = 1; i <= m; ++i) 41 scanf("%d%d",&a[i].x,&a[i].y); 42 for(int i = 1; i <= n; ++i) 43 cun[i] = i; 44 int cnt = 1; 45 for(int i = 1; i <= m; ++i) 46 { 47 if(find(a[i].x) != find(a[i].y)) 48 { 49 shu(a[i].x,a[i].y); 50 cnt++; 51 } 52 } 53 cout << n - cnt << endl; 54 } 55 return 0; 56 }
hdu 1232 畅通工程(最小生成树),布布扣,bubuko.com
原文:http://www.cnblogs.com/Unico-liyang/p/3894489.html