原理可以看上一节:【数据结构】之实现并查集
下面对并查集进行简单的封装:
头文件union_find.h:
#ifndef INC_6_FOOD_LINK_UNION_H
#define INC_6_FOOD_LINK_UNION_H
#include <malloc.h>
#include <memory.h>
typedef struct UnionFind{
unsigned int size;
int *par;
int *rank;
int (*findRoot)(struct UnionFind*, int);
void (*unite)(struct UnionFind*, int, int);
int (*same)(struct UnionFind*, int, int);
void (*delete)(struct UnionFind*);
} UnionFind;
//构造函数
UnionFind* new_UnionFind(unsigned int);
//查找树的根
int findRoot(UnionFind*, int);
//合并
void unite(UnionFind*, int, int);
//判断两个元素是否属于同一集合
int same(UnionFind*, int, int);
//释放
void delete(UnionFind*);
#endif //INC_6_FOOD_LINK_UNION_H
实现union_find.c:
#include "union_find.h"
extern UnionFind* new_UnionFind(unsigned int size){
UnionFind *unionFind = malloc(sizeof(UnionFind));
unionFind->size = size;
unionFind->par = malloc(sizeof(int) * size);
unionFind->rank = malloc(sizeof(int) * size);
for (int i = 0; i < size; ++i) {
unionFind->par[i] = i;
}
memset(unionFind->rank, 0, sizeof(int) * size);
unionFind->findRoot = &findRoot;
unionFind->unite = &unite;
unionFind->same = &same;
unionFind->delete = &delete;
return unionFind;
}
extern int findRoot(UnionFind* uf, int x){
int *par = uf->par;
if (x == par[x])
return x;
return par[x] = findRoot(uf, par[x]);
}
extern void unite(UnionFind* uf, int x, int y){
x = findRoot(uf, x);
y = findRoot(uf, y);
if (x == y)
return;
if (uf->rank[x] < uf->rank[y]){
uf->par[x] = uf->par[y];
} else {
uf->par[y] = uf->par[x];
if (uf->rank[x] == uf->rank[y])
uf->rank[x]++;
}
}
int same(UnionFind* uf, int x, int y){
return findRoot(uf, x) == findRoot(uf, y);
}
void delete(UnionFind* uf){
free(uf->par);
free(uf->rank);
free(uf);
}
下一篇打算用这个封装解决一个食物链问题:【数据结构】之利用并查集解决食物链问题