首页 > 其他 > 详细

F-找朋友(裸并查集)

时间:2019-12-15 20:12:35      阅读:114      评论:0      收藏:0      [点我收藏+]

题目链接: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行:每行两个数Mi?Mj?1Mi?,Mj?n,表示Mi?Mj?具有朋友关系。

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

 

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\n");
        else printf ("Yes\n");
    }
    return 0;
}

 

F-找朋友(裸并查集)

原文:https://www.cnblogs.com/lonely-wind-/p/12003824.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!