题目背景
若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。
题目描述
规定:x 和 y 是亲戚,y 和 z 是亲戚,那么 x 和 z 也是亲戚。如果 x,y 是亲戚,那么 x 的亲戚都是 y 的亲戚,y 的亲戚也都是 x 的亲戚。
输入格式
第一行:三个整数 n,m,p,(n,m,p≤5000),分别表示有 n 个人,m 个亲戚关系,询问 p 对亲戚关系。
以下 m 行:每行两个数 Mi,Mj,1≤Mi, Mj≤N,表示 Mi 和Mj 具有亲戚关系。
接下来 p 行:每行两个数 Pi,Pj,询问 Pi 和 Pj 是否具有亲戚关系。
输出格式
p 行,每行一个 Yes
或 No
。表示第 i 个询问的答案为“具有”或“不具有”亲戚关系。
输入输出样例
输入 #1复制
6 5 3 1 2 1 5 3 4 5 2 1 3 1 4 2 3 5 6
输出 #1复制
Yes Yes No
这是非递归的版本,带有路径压缩!,具体请看有代码注释!
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <vector>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
const int N=5005;
int n,m,p;
int fa[N];//记录谁是祖先的数组
int find(int x) {
int t=x;//记录祖先节点
while(t!=fa[t])//查找祖先节点
t=fa[t];
while(x!=fa[x]) { //路径压缩:把所有的子孙全部指向最开始的祖先
int temp=fa[x];//记录当前的祖先,后面会改变fa[x]的值
fa[x]=t;//指向最开始的祖先
x=temp;//当前祖先作为子孙,下一次找当前祖先的祖先
}
return x;
}
void merge(int a,int b) {
a=find(a);
b=find(b);
if(a!=b)//如果两人的祖先不是一个人,就合并两人的祖先
fa[b]=a;//这里是让一个人当祖先
}
//这是merge调用的数据模拟,辅助理解
//fa[2]=1;
//fa[1]=1;
//fa[1]=1;
//fa[5]=1;
//fa[4]=3;
//fa[3]=3;
//fa[1]=1;
//fa[3]=1;
int main() {
scanf("%d%d%d",&n,&m,&p);
for(int i=1; i<=n; i++)
fa[i]=i;//刚开始每个人都是自己的祖先!
while(m--) { //通过给出的关系,确定祖先
int a,b;
scanf("%d%d",&a,&b);
merge(a,b);//是亲戚就合并祖先
}
while(p--) {
int a,b;
scanf("%d%d",&a,&b);
if(find(a)==find(b))
puts("Yes");
else
puts("No");
}
return 0;
}