洛谷 P1551 亲戚

 本质还是并查集,模板套用一下就可以了,挺简单

 

#include<iostream>
using namespace std;

#define MAX_TREE_SIZE 10010
int parent[MAX_TREE_SIZE]={0};//创建一个结点数组 
int deep[MAX_TREE_SIZE]={0}; 
void initial(int n)//初始化 
{
	for(int i=0;i<n;i++)
	{
		parent[i]=-1;
		deep[i]=0;
	}
}

int find_root(int x)//寻找根结点 
{
	int x_root=x;
	while(parent[x_root]!=-1)
	{
		x_root=parent[x_root];
	}
	return x_root;
}

void combine(int x,int y)//连接亲戚关系 
{
	int x_root=find_root(x);
	int y_root=find_root(y);
	if(x_root!=y_root)
	{
		if(deep[x_root]>deep[y_root])
		{
			parent[y_root]=x_root;
		}
		else if(deep[x_root]<deep[y_root])
		{
			parent[x_root]=y_root;
		}
		else
		{
			parent[x_root]=y_root;
			deep[y_root]++;//结点深度+1 
		}
	}
}

void check(int x,int y)//查询是否具有亲戚关系 
{
	int x_root=find_root(x);
	int y_root=find_root(y);
	if(x_root==y_root)
		cout<<"Yes"<<endl; 
	else
		cout<<"No"<<endl;
}

int main()
{
	int n,m,p;
	cin>>n>>m>>p;// n 个人,m 个亲戚关系,询问 p 对亲戚关系
	initial(n);//初始化 
	
	int Mi,Mj;
	for(int i=0;i<m;i++)
	{
		cin>>Mi>>Mj;//输入亲戚关系 
		combine(Mi,Mj);//连接亲戚关系 
	}
	
	int Pi,Pj;
	for(int i=0;i<p;i++)
	{
		cin>>Pi>>Pj;
		check(Pi,Pj);//查询是否具有亲戚关系
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值