本质还是并查集,模板套用一下就可以了,挺简单
#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);//查询是否具有亲戚关系
}
}