F-找朋友(裸并查集)

题目链接:http://acm.csust.edu.cn/problem/3029

Description

 

——你要是愿意,我就永远存在

某人的朋友圈实在是过于庞大且复杂,要判断两个人是不是朋友,那还真不容易。

现给出某个朋友圈关系图,求任意给出的两个人是否是朋友。

规定:如果x和yy是朋友,y和z是朋友,那么x和z也是朋友。

如果x和y是朋友,那么x的朋友都是y的朋友,y的朋友也都是x的朋友。

Input

 

第一行:三个整数n,m,p,(n50000,m50000,p50000),分别表示有n个人,m个朋友关系,询问p对朋友关系。

以下m行:每行两个数MiMj1Mi,Mjn,表示MiMj具有朋友关系。

接下来p行:每行两个数PiPj,询问PiPj是否具有朋友关系。

Output

 

P行,每行一个“Yes”或“No”(不包含引号)。表示第i个询问的答案为“具有”或“不具有”朋友关系。

Sample Input 1 

6 5 3
1 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6

Sample Output 1

Yes
Yes
No

裸的并查集,不知道为什么那么多人没过。。。QAQ

   解法:裸的并查集的路径压缩或按秩合并

以下是AC代码:

#include <bits/stdc++.h>
using namespace std;

const int mac=5e4+10;

int father[mac];

int find(int x)
{
    return x==father[x]?x:father[x]=find(father[x]);
}

int main()
{
    int n,m,p;
    scanf ("%d%d%d",&n,&m,&p);
    for (int i=1; i<=n; i++)
        father[i]=i;
    for (int i=1; i<=m; i++){
        int u,v;
        scanf ("%d%d",&u,&v);
        int fa=find(u),fb=find(v);
        if (fa!=fb){
            father[fa]=fb;
        }
    }
    for (int i=1; i<=p; i++){
        int u,v;
        scanf ("%d%d",&u,&v);
        int fa=find(u),fb=find(v);
        if (fa!=fb) printf ("No
");
        else printf ("Yes
");
    }
    return 0;
}
路漫漫兮
原文地址:https://www.cnblogs.com/lonely-wind-/p/12003824.html