并查集
typedef struct ufs_elem_st {
struct ufs_elem_st *next, *prev;
struct ufs_elem_st *parent;
} ufs_elem_st, *ufs_elem_t;
typedef struct ufs_st {
ufs_elem_st *roots;
} ufs_st, *ufs_t;
ufs_elem_t ufs_get_root(ufs_elem_t me) {
ufs_elem_t my_root = me;
while( my_root->parent != my_root && my_root->parent != NULL )
my_root = my_root->parent;
me->parent = my_root; //路径压缩
return my_root;
}
void ufs_add_root(ufs_t ufs, ufs_elem_t me) {
ufs_elem_t my_root = ufs_get_root(me);
if( NULL != ufs->roots ) {
my_root->next = ufs->roots;
ufs->roots->prev = my_root;
}
ufs->roots = my_root;
my_root->prev = NULL;
}
void ufs_join(ufs_t ufs, ufs_elem_t friend_elem, ufs_elem_t me) {
ufs_elem_t my_root = ufs_get_root(me);
ufs_elem_t friend_root = ufs_get_root(friend_elem);
if( NULL != my_root->next )
my_root->next->prev = my_root->prev;
if( NULL != my_root->prev )
my_root->prev->next = my_root->next;
if( ufs->roots == my_root )
ufs->roots = my_root->next;
my_root->next = my_root->prev = NULL;
if( NULL != friend_root->next )
friend_root->next->prev = friend_root->prev;
if( NULL != friend_root->prev )
friend_root->prev->next = friend_root->next;
if( ufs->roots == friend_root )
ufs->roots = friend_root->next;
friend_root->next = friend_root->prev = NULL;
//合并集合
friend_root->parent = my_root;
if( NULL != ufs->roots ) {
my_root->next = ufs->roots;
ufs->roots->prev = my_root;
}
ufs->roots = my_root;
my_root->prev = NULL;
}