php 简单并查集实现

<?php
$n    = 10;//10个结点
$case = 7; //7组关系,如下
$data = array(
		array(2,4),
		array(7,5),
		array(1,3),
		array(8,9),
		array(1,2),
		array(5,6),
		array(2,3),
		);

$UFSTree = array();

function Make_Set(&$UFSTree,$n)
{
	for($i=1;$i<=$n;$i++)
	{
		$UFSTree[$i]['data']  =$i;
		$UFSTree[$i]['parent']=$i;
		$UFSTree[$i]['rank']  = 0; //初始化高度为0
	}
}

function Find_Set(&$UFSTree,$x)
{
	if($x!=$UFSTree[$x]['parent'])
	{
		return Find_Set($UFSTree, $UFSTree[$x]['parent']);
	}
	else
		return $x;
}

function Union(&$UFSTree,$x,$y)
{
	$x = Find_Set($UFSTree, $x);
	$y = Find_Set($UFSTree, $y);
	
	if($UFSTree[$x]['rank']>$UFSTree[$y]['rank'])
	{
		$UFSTree[$y]['parent']=$x;
	}
	else
	{
		$UFSTree[$x]['parent'] = $y;
		if($UFSTree[$x]['rank']==$UFSTree[$y]['rank'])
		{
			$UFSTree[$y]['rank']++;
		}
	}
}

//判断 
//3,4
//7,10
//8,9
//是否是亲戚
$search = array(
		array(3,4),
		array(7,10),
		array(8,9)
		);

//初始化
Make_Set($UFSTree, $n);
var_dump($UFSTree);

//合并关系

foreach ($data as $da)
{
	Union($UFSTree,$da[0], $da[1]);
}

var_dump($UFSTree);


//查找是否属于同一个祖先
foreach ($search as $s)
{
	if(Find_Set($UFSTree, $s[0])==Find_Set($UFSTree, $s[1]))
	{
		echo $s[0],',',$s[1],'  are relative </br>';
	}
	else 
	{
		echo $s[0],',',$s[1],'  not are relative</br>';
	}
}



?>
杭电OJ 1213 c 实现
#include <stdio.h>
#include <string.h>
struct node
{
	int parent;
	int rank;
	int data;
}nodes[1002];

void Make_Set(int n)
{
	int i;
	for(i=1;i<=n;i++)
	{
		nodes[i].data   = i;
		nodes[i].parent = i;
		nodes[i].rank   = 0;
	}
}

int find_set(int x)
{
	if(x!=nodes[x].parent)
		return find_set(nodes[x].parent);
	return x;
}

void Union(int x,int y)
{
	x=find_set(x);
	y=find_set(y);
	if(nodes[x].rank>nodes[y].rank)
	{
		nodes[y].parent = x;
	}
	else
	{
		nodes[x].parent = y;
		if(nodes[x].rank = nodes[y].rank)
		{
			nodes[y].rank++;
		}
	}
}
int main()
{
	int ncase;
	int n,t,i;
	int x,y,num;
	int c[1002];

	scanf("%d",&ncase);
	while(ncase--)
	{
		num=0;
		i=0;
		memset(c,0,sizeof(c));

		scanf("%d %d",&n,&t);
		Make_Set(n);

		while (i<t)
		{
			scanf("%d %d",&x,&y);

			Union(x,y);

			i++;
		}
		for(i=1;i<=n;i++)
		{
			x= find_set(i);
			if(c[x]==0)
			{
				num++;
				c[x]++;
			}
			else
			{
				c[x]++;
			}
		}
		printf("%d\n",num);
	}
	return 0;
}


并查集一位数组模拟非递归查找:
int Find_set(int x)
{
    int r=x;
    while(r!=set[r])
        r=set[r];
    return r;
}
void Union_set(int x,int y)
{
    int fx,fy;
    fx=find_x(x);
    fy=find_x(y);
    if(fx<fy)
        set[fx]=fy;
    else
        set[fy]=fx;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值