简单并查集

#include<iostream>
using namespace std;

int height[ 100 ];
int root[ 100 ];

int find_root( int x ) {
	//只有根节点存在x == root[ x ]
	if( x != root[ x ] ) {
		root[ x ] = find_root( root[ x ] );
	}
	return root[ x ];
}

void Union( int a , int b ) {
	//低树并入高树
	if( height[ a ] > height[ b ] ) {
		root[ b ] = a;
	}
	else {
		root[ a ] = b;
		//如果树一样高,则高度加1
		if( height[ a ] == height[ b ] ) {
			height[ a ] ++;
		}
	}
}
int main() {
	//有m个人,其中有q对亲戚,判断另外p对是否是亲戚
	int m , q , p;
	int a , b;
	//输入,总共人数,给出的亲戚对数,以及问题数
	cin >> m >> p >> q;
	for( a = 0 ; a <= m ; a ++ ) {
		height[ a ] = 0;
		root[ a ] = a;
	}
	while( p -- ) {
		//输入a和b是亲戚
		cin >> a >> b;
		//合并是对根的合并
		Union( find_root( a ) , find_root( b ) );
	}
	while( q -- ) {
		//判断a和b是否是亲戚
		cin >> a >> b;
		if( find_root( a ) == find_root( b ) ) {
			cout << "YES" << endl;
		}
		else {
			cout << "NO\n";
		}
	}
}
/*
10 5 5
1 2
2 5
3 6
7 3
8 9
1 3
2 4
5 6
5 5
6 7
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值