首页 > 其他 > 详细

不相交集实现实例

时间:2014-04-22 11:08:06      阅读:541      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
/* 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 */
bubuko.com,布布扣
bubuko.com,布布扣
/* 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);
}
bubuko.com,布布扣

测试函数:

bubuko.com,布布扣
/* 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;
}
bubuko.com,布布扣

Makefile:

bubuko.com,布布扣
/* Makefile */

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

clean:
    rm *.o test
bubuko.com,布布扣

测试过程:

bubuko.com,布布扣

不相交集实现实例,布布扣,bubuko.com

不相交集实现实例

原文:http://www.cnblogs.com/nufangrensheng/p/3679661.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!