1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| #include <stdio.h> #include <stdlib.h>
typedef struct UnionFind { int* parent; int* rank; int size; int count; } UnionFind;
UnionFind* create_union_find(int n) { UnionFind* uf = (UnionFind*)malloc(sizeof(UnionFind)); uf->parent = (int*)malloc(n * sizeof(int)); uf->rank = (int*)calloc(n, sizeof(int)); uf->size = n; uf->count = n; for (int i = 0; i < n; i++) { uf->parent[i] = i; } return uf; }
int find(UnionFind* uf, int x) { if (uf->parent[x] != x) { uf->parent[x] = find(uf, uf->parent[x]); } return uf->parent[x]; }
void union_sets(UnionFind* uf, int x, int y) { int root_x = find(uf, x); int root_y = find(uf, y); if (root_x != root_y) { if (uf->rank[root_x] < uf->rank[root_y]) { uf->parent[root_x] = root_y; } else if (uf->rank[root_x] > uf->rank[root_y]) { uf->parent[root_y] = root_x; } else { uf->parent[root_y] = root_x; uf->rank[root_x]++; } uf->count--; } }
bool connected(UnionFind* uf, int x, int y) { return find(uf, x) == find(uf, y); }
int main() { UnionFind* uf = create_union_find(10); union_sets(uf, 0, 1); union_sets(uf, 1, 2); union_sets(uf, 3, 4); printf("0和2是否连通: %s\n", connected(uf, 0, 2) ? "是" : "否"); printf("0和3是否连通: %s\n", connected(uf, 0, 3) ? "是" : "否"); printf("连通分量数: %d\n", uf->count); return 0; }
|