【HDOJ】1232 畅通工程
并查集Union-Find,经典题目。而且也真的感受到了并查集提高的效率,之前写的O(n^3)的遍历,果然TLE。换并查集后,测试998 0数据时感受到了明显的快。
1 #include <stdio.h> 2 3 #define MAXNUM 1005 4 5 int path[MAXNUM]; 6 7 int _find(int a) { 8 int i = a; 9 while (i != path[i]) 10 i = path[i]; 11 return i; 12 } 13 14 void _union(int a, int b) { 15 int i = _find(a); 16 int j = _find(b); 17 if (i != j) path[j] = i; 18 } 19 20 int main() { 21 int n, m, num; 22 int i, j, k; 23 24 while (scanf("%d", &n)!=EOF && n) { 25 scanf("%d", &m); 26 num = 0; 27 for (i=1; i<=n; ++i) 28 path[i] = i; 29 for (i=0; i<m; ++i) { 30 scanf("%d %d", &j, &k); 31 _union(j, k); 32 } 33 for (i=1; i<=n; ++i) 34 if (path[i] == i) 35 num++; 36 printf("%d\n", num-1); 37 } 38 39 return 0; 40 }