在社交的過程中,通過朋友,也能認識新的朋友。在某個朋友關係圖中,假定 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<stdio.h>
#include <string.h>
#include <math.h>
#include <stack>
using namespace std;
int n,m,p,father[6000];
int get(int x)
{
if(father[x]==x)
{
return x;
}
return father[x]=get(father[x]);
}
void merge(int x,int y)
{
x=get(x);
y=get(y);
if(x!=y)
{
father[y]=x;
}
}
int check(int x,int y)
{
if(get(x)==get(y))
{
return 1;
}else
{
return 0;
}
}
int main()
{
cin>>n>>m>>p;
for(int i=1;i<=n;i++)
{
father[i]=i;
}
for(int i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
merge(x,y);
}
for(int i=1;i<=p;i++)
{
int q1,q2;
cin>>q1>>q2;
if(check(q1,q2))
{
printf("Yes\n");
}else
{
printf("No\n");
}
}
return 0;
}