并查集的实现c


#ifndef _UNION_SET_H_
#define _UNION_SET_H_


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/*
  *This file is about union set operations.
  *and the program is c-style,you can transfer it to 
  *cpp-style.
  *you can copy,re-write,sell this program but no need to
  *let me know this.but you need copy this comment to your
  *program's header comment.
  *hujian nankai university
  *2016/5/26
*/

#define UNION_SET_MAX_SIZE 1024*10 //the size of union.

//the parent array
int parent[UNION_SET_MAX_SIZE];

//the height of the union tree
int rank[UNION_SET_MAX_SIZE];

//the size of union
int union_size=0;


//initialze the union set
void init_set()
{
    int i;
    for(i=0;i<union_size;i++){
        parent[i]=i;
        rank[i]=0;
    }
}

//find the root of this tree
int find_set(int x){
    if(x==parent[x]){
        return x;
    }else{
       return parent[x]=find_set(parent[x]);
    }
}

//union x and y is the root of each tree
void union_set(int x,int y)
{
    x=find_set(x);
    y=find_set(y);
    if(x==y) return;//same tree
    if(rank[x]<rank[y]){
       //the height x<height y
       //then,let the y as the root
       parent[x]=y;
    }else{
        parent[y]=x;
        if(rank[x]==rank[y]){
            rank[x]++;
        }
    }
}

//judge if the x and y is the same tree
bool same_set(int x,int y)
{
   return find_Set(x)==find_Set(y);
}

#endif //end of union set
///<hujian 2016/5/26>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值