C语言实现,Union-Find算法

#include <stdio.h>
#define NUM 10
int point[NUM];
int point_size[NUM] = {1};
/*初始化,每个数值的值表示为一个分组的序号*/
void init()
{
        int i;

        for(i = 0;i < NUM;i++)
                point[i] = i;
        return;
}
/*查找一个节点的分组的“根”序号*/
int find(int p)
{
        while (point[p] != p) {
                /*为了个使树深度更小*/
                point[p] = point[point[p]];
                p = point[p];
        }
        return p;
}
/*使两个节点化为同一分组,小树向大树靠拢*/
void connect(int p, int q)
{
        int r_p, r_q;

        r_p = find(p);
        r_q = find(q);
        if (point_size[r_p] >= point[r_q]){
                point[r_q] = point[r_p];
                point_size[r_p] += point_size[r_q];
        }   
        else { 
                point[r_p] = point[r_q];
                point_size[r_q] += point_size[r_p];
        }   
}
/*判断两个节点是否为同一分组*/
int  isconnect(int p, int q)
{
        return (find(p) == find(q))?1:0;
}

int main(int argc, char* argv[])
{
        int flag, a, b;
        init();
        while (1) {
                printf("Enter your choice(0:quit;1:add edge;):\n");
                scanf("%d", &flag);
                if ((flag != 1)&&(flag != 0)) {
                        printf("Your choice is wrong,please try again!\n");
                        continue;
                }
                if (flag == 0) {
                        printf("quit\n");
                        break;
                }
                else  {
                        printf("Enter the two point:\n");
                        scanf("%d %d", &a, &b);
                        if (isconnect(a, b)) {
                                printf("the two point in one union already!\n");
                                continue;
                        }
                        else {
                                connect(a, b);
                                printf("connect succeed!\n");
                        }
                }
        }
        return 1;
}


此Union-Find算法,可以对多个点进行“分组”,判断多个点是否为一个分组,未实现输出路径的操作














你可能感兴趣的:(C语言实现,Union-Find算法)