並查集實現(C語言)
阿新 • • 發佈:2018-12-24
實現了最基本的並查集,可以用巨集 path_compress 開關路徑壓縮.
#include<stdio.h> #include<stdlib.h> #include<memory.h> #define MAXNUM 20 int parent[MAXNUM]; int find_set(int x) { int ret = x; #define path_compress 1 #if path_compress //遞迴,帶路徑壓縮 if ( x!=parent[x]) { parent[x] = find_set(parent[x]); } #else // 遞推,非路徑壓縮 while (ret != parent[ret]) { ret = parent[ret]; } #endif return parent[x]; } int union_set(int a, int b) { int rootA = find_set(a); int rootB = find_set(b); if (rootA == rootB) { return 0; } // 合併後的集合編號取較小者 if (a < b) parent[b] = a; else parent[a] = b; return 0; } int main(int argc, char** argv) { int i, a, b; for(i = 0; i < 20; ++i) { parent[i] = i; } freopen("test_unionset.in", "r", stdin); while(EOF != scanf("%d %d", &a, &b)) { union_set(a, b); printf("set of %d and %d is %d\n", a, b, find_set(a)); } printf("============================\n"); for(i = 0; i < 20; ++i) { printf("%-3d", i); } printf("\n"); for(i = 0; i < 20; ++i) { printf("%-3d", find_set(i) ); } printf("\n"); return 0; }