题目描述
若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。
规定:x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。如果x,y是亲戚,那么x的亲戚都是y的亲戚,y的亲戚也都是x的亲戚。
输入格式
第一行:三个整数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是否具有亲戚关系。
输出格式
P行,每行一个’Yes’或’No’。表示第i个询问的答案为“具有”或“不具有”亲戚关系。
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <stack>
#include <set>
using namespace std;
const int MAX = 50010;
int father[MAX];
int findFather(int x)
{
int F = x;
while(F != father[F]) F = father[F];
while(x != F)
{
int temp = x;
x = father[x];
father[temp] = F;
}
return F;
}
void Union(int a, int b)
{
int aF = findFather(a);
int bF = findFather(b);
father[bF] = aF;
}
int main()
{
int N, M, P, A, B;
scanf("%d %d %d", &N, &M, &P);
for(int i = 1; i <= N; i++) father[i] = i;
for(int i = 0; i < M; i++)
{
scanf("%d %d", &A, &B);
Union(A, B);
}
for(int i = 0; i < P; i++)
{
scanf("%d %d", &A, &B);
int aF = findFather(A);
int bF = findFather(B);
if(aF != bF) printf("No\n");
else printf("Yes\n");
}
system("pause");
return 0;
}