用于不相交集合的数据结构(并查集)

 

#pragma once

template 
struct Node {
	Node(const _Ty& d) : data(d) {}

	_Ty data;
	int rank = 0;
	Node<_Ty>* p = nullptr;
};

template 
void make_set(Node<_Ty>* node) {
	node->p = node;
	node->rank = 0;
}

template 
void __link(Node<_Ty>* lhs, Node<_Ty>* rhs) {
	if (lhs->rank > rhs->rank) {
		rhs->p = lhs;
	} else {
		lhs->p = rhs;
		if (lhs->rank == rhs->rank) {
			rhs->rank++;
		}
	}
}

template 
void union_set(Node<_Ty>* lhs, Node<_Ty>* rhs) {
	__link(find_set(lhs), find_set(rhs));
}

template 
Node<_Ty>* find_set(Node<_Ty>* node) {
	if (node != node->p) {
		node = find_set(node->p);
	}
	return node;
}

 

你可能感兴趣的:(数据结构)