在社交的过程中,通过朋友,也能认识新的朋友。在某个朋友关系图中,假定 A 和 B 是朋友,B 和 C 是朋友,那么 A 和 C 也会成为朋友。即,我们规定朋友的朋友也是朋友。
现在,已知若干对朋友关系,询问某两个人是不是朋友。
请编写一个程序来解决这个问题吧。
输入格式
第一行:三个整数 n,m,p (n\leq 5000,m\leq 5000,p\leq 5000)n,m,p(n≤5000,m≤5000,p≤5000),分别表示有 nn 个人,mm 个朋友关系,询问 pp对朋友关系。
接下来 mm 行:每行两个数 A_i,B_iAi,Bi,1\leq A_i,B_i\leq N1≤Ai,Bi≤N,表示 A_iAi 和 B_iBi 具有朋友关系。
接下来 pp 行:每行两个数,询问两人是否为朋友。
输出格式
输出共 pp 行,每行一个Yes
或No
。表示第 ii 个询问的答案为是否朋友。
样例输入
6 5 3 1 2 1 5 3 4 5 2 1 3 1 4 2 3 5 6
样例输出
Yes Yes No
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int father[5010];
int get(int a)
{
if(father[a]==a)
return a;
else
return father[a]=get(father[a]);
}
void add(int a,int b)
{
a=get(a);
b=get(b);
if(a!=b)
{
father[a]=b; //注意是让b的根节点成为"a的根节点"的根节点
}
}
int main()
{
int n,m,p;
cin>>n;
for(int i=1;i<=n;i++)
father[i]=i;
cin>>m;
cin>>p;
while(m--)
{
int a,b;
cin>>a>>b;
add(a,b);
}
while(p--)
{
int a,b;
cin>>a>>b;
if(get(a)==get(b))
cout<<"Yes";
else
cout<<"No";
if(p!=0)
cout<<endl;
}
return 0;
}