算法导论-带路径压缩的不相交集合C++实现

算法导论-带路径压缩的不相交集合C++实现

//带路径压缩的不相交集合
template
struct Set
{
	int m_rank; //秩
	Set* m_parent; //父节点
	Type* m_data; //数据
};

template
Set* MakeSet(Type* data)
{
	Set* node = new Set;
	node->m_parent = node;
	node->m_rank = 0;
	node->m_data = data;
	return node;
}

template
void DestroySet(Set* set)
{
	if(set != NULL)
		delete set;
}

template
Set* Union(Set* x,Set* y)
{
	return Link(FindSet(x),FindSet(y));
}

template
Set* Link(Set* x,Set* y)
{
	if(x == NULL || y == NULL)
		return x != NULL? x : y;
	Set* node = x;
	if(x->m_rank>y->m_rank)
	{
		y->m_parent = x;
	}
	else
	{
		node = y;
		x->m_parent = y;
		if(x->m_rank == y->m_rank)
			y->m_rank++;
	}
	return node;
}

template
Set* FindSet(Set* x)
{
	if(x == NULL)
		return NULL;
	if(x != x->m_parent)
	{
		x->m_parent = FindSet(x->m_parent); //路径压缩
	}
	return x->m_parent;
}

template
void PrintSet(Set *x) 
{
	if(x != NULL)
		printf("data:%p,rank:%d,parent:%p,root:%p\n",x->m_data,x->m_rank,x->m_parent->m_data,FindSet(x)->m_data);
}

int main(int argc, char* argv[])
{	
	int i=0;
	Set* set[20];
	int data[20];
	for(i=0;i(data+i);
	}
	
	for(i=0;i(set[i]);
	}
        return 0;
}

你可能感兴趣的:(C++,练习,算法,数据结构,算法导论)