jzoj1882-亲戚【并查集】

题目

有n个人,已知m种亲戚关系,如果A和B是亲戚,B和C也是亲戚,那么A和C也是亲戚。接下来求一些人是否为亲戚。

Input

输入由两部分组成。
第一部分以N,M开始。N为问题涉及的人的个数,M表示已经知道M对亲戚关1<=N,M<=100000,接下来M行,每行有两个数ai, bi,表示已知ai和bi是亲戚。这些人的编号为1,2,3,…, N。接下来输入一个整数P(1<=P<=100000),表示有P次询问,接下来P行,每行为ci, di,表示询问ci和di是否为亲戚。

Output

输出一行:若ci和di为亲戚,则输出“Yes”,否则输出“No”。

Sample Input

10 7
2 4
5 7
1 3
8 9
1 2
5 6
2 3
3
3 4
7 10
8 9

Sample Output

Yes
No
Yes

解题思路

并查集不解释

代码

#include
using namespace std;
int x,y,father[100001],n,m,p;
int find(int x)//查找
{
    if (x!=father[x]) return father[x]=find(father[x]);
    else return x;
}
void d(int x,int y)
{
    int fa=find(x),fb=find(y);
    if (faelse father[fa]=fb;
}
int main()
{
    scanf("%d%d",&n,&m);    
    for (int i=1;i<=n;i++) father[i]=i;
    for (int i=1;i<=m;i++)
    {
        scanf("%d%d",&x,&y);
        d(x,y);//合并
    }
    scanf("%d",&p);
    for (int i=1;i<=p;i++)
    {
        scanf("%d%d",&x,&y);
        if (find(x)!=find(y)) printf("No\n");//询问
        else printf("Yes\n");
    }
}

你可能感兴趣的:(图论)