不相交集实现实例

不相交集类型声明及函数实现:

/* disjoint_set.h */

#ifndef _DISJOINT_SET_H
#define _DISJOINT_SET_H

#define NUMSETS    5
typedef int disjoint_set[NUMSETS + 1];
typedef int set_type;
typedef int element_type;

void initialize(disjoint_set s);
void set_union(disjoint_set s, set_type root1, set_type root2);
set_type find(element_type x, disjoint_set s);

#endif /* _DISJOINT_SET_H */
/* disjoint_set.c */

#include "disjoint_set.h"

void 
initialize(disjoint_set s)
{
    int i;
    
    for(i = NUMSETS; i > 0; i--)
        s[i] = 0;
}

void 
set_union(disjoint_set s, element_type x1, element_type x2)
{
    set_type root1, root2;
    root1 = find(x1, s);
    root2 = find(x2, s);
    s[root2] = root1;
}

set_type 
find(element_type x, disjoint_set s)
{
    if(s[x] <= 0)
        return x;
    else
        return find(s[x], s);
}

测试函数:

/* disjoint_set_test.c */

#include "disjoint_set.h"
#include <stdio.h>

int
main(void)
{
    disjoint_set s;
    initialize(s);
    set_union(s, 1, 2);
    set_union(s, 3, 4);
    set_union(s, 5, 1);
    set_union(s, 4, 2);

    if(find(1, s) == find(3, s))
        printf("1 and 3 are joint\n");
    else
        printf("1 and 3 are not joint\n");
    
    return 0;
}

Makefile:

/* Makefile */

target := test
objs := disjoint_set_test.o disjoint_set.o  
$(target):$(objs)
    gcc -o $@ $^
%.o:%.c
    gcc -c -o $@ $<

clean:
    rm *.o test

测试过程:

image

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值