[Description]
Teoy最近迷上了阿里巴巴面向网商和中小企业主开发的BNS(Business Network Service)网站“来往”(www.laiwang.com),在那里他可以结交生意上的朋友,包括上游供应商以及下游的客户。随着业务的
扩大,Teoy迫切想认识自己好友列表之外的更多的同行。他提出这样一个问题,给出任意的A和B,他想知
道在“来往”上A能不能间接认识到B。
[Input]
一共有 T 组测试数据。每组数据第一行为三个整数 n,m 和 q,表示人数,给出的关系数和询问数。
接下来共 n 行,每行 2 个整数 x 和 y。表示 x 和 y 认识。
接下来 q 行,表示 q 组询问,q 行每行 2 个整数 x 和 y,表示询问 x 和 y 能否间接认识。
0<t<=100
0<n,m,q<=200
[Output]
对每组数据,给出 q 行,每行分别是“Yes”和“No”,分别回答 x 和 y 是否认识或间接认识。
[Sample Input]
2
3 2 2
1 2
1 3
2 3
1 2
5 3 1
2 3
1 2
3 4
1 4
[Sample Output]
Yes
Yes
Yes
[Source]
3230391@BUPTACM
思路:
并查集(可能是我水过最多的算法)
代码:
#include<iostream>
using namespace std;
int father[205];
int find_father(int x)
{
if(x!=father[x])
return find_father(father[x]);
return x;
}
void union_set(int a,int b)
{
int father_a = find_father(a);
int father_b = find_father(b);
if(father_a!=father_b)
father[father_a] = father_b;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m,q,a,b;
scanf("%d %d %d",&n,&m,&q);
for(int i=1;i<=n;i++)
father[i] = i;
for(int i=0;i<m;i++)
{
scanf("%d %d",&a,&b);
union_set(a,b);
}
for(int i=0;i<q;i++)
{
scanf("%d %d",&a,&b);
if(find_father(a)==find_father(b)) printf("Yes\n");
else printf("No\n");
}
}
}