【并查集】亲戚

Description

若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。

规定:x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。如果x,y是亲戚,那么x的亲戚都是y的亲戚,y的亲戚也都是x的亲戚。

Input

第一行:三个整数n,m,p,(n<=5000,m<=5000,p<=5000),分别表示有n个人,m个亲戚关系,询问p对亲戚关系。

以下m行:每行两个数Mi,Mj,1<=Mi,Mj<=N,表示Ai和Bi具有亲戚关系。

接下来p行:每行两个数Pi,Pj,询问Pi和Pj是否具有亲戚关系。

Output

P行,每行一个’Yes’或’No’。表示第i个询问的答案为“具有”或“不具有”亲戚关系。

Sample Input

6 5 31 21 53 45 21 31 42 35 6

Sample Output

YesYesNo

Code:

#include <iostream>

#define SIZE 5001

using namespace std;

class unionset
{
	public:
		int pre[SIZE]; // 记录上面一个节点
		
		int findfather(int x) // 找一个结点的祖先
		{
			if (pre[x]) // 如果上面还有节点,继续找
			{
				int t = findfather(pre[x]); // 找自己上层的节点
				pre[x] = t; // 必要的路径压缩,大大省时
				return t;
			}
			
			return x; // 上面没有节点了,自己的祖先就是自己
		}
		
		void join(int x, int y) // 合并两个节点
		{
			int t1 = findfather(x), t2 = findfather(y); // 开始找这两个节点的祖先
			
			if (t1 != t2) // 如果两个节点的祖先不同
			{
				pre[t1] = t2; // 就让其中一个节点变成另一个节点的上层节点
			}
		}
		
		bool check(int x, int y) // 判断两个节点是否连通
		{
			return (findfather(x) == findfather(y)); // 如果它们的祖先是一样的,就表面两个节点连通
		}
};

unionset a;

int main(int argc, char** argv) // 主函数!
{
	int n, m, p, i, x, y;
	
	scanf("%d%d%d", &n, &m, &p);
	while (m--)
	{
		scanf("%d%d", &x, &y);
		a.join(x, y); // 连通两个节点
	}
	
	while (p--)
	{
		scanf("%d%d", &x, &y);
		if (a.check(x, y)) // 判断是否连通
		{
			cout << "Yes" << endl;
		}
		else
		{
			cout << "No" << endl;
		}
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/80917955
今日推荐