P1551 亲戚 【并查集】

题目

https://www.luogu.com.cn/problem/P1551

 

 思路

使用并查集进行关系的记录

注意father函数的初始化!!!

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int father[6000], ranks[6000];
int find(int x)
{
    if (father[x] == x)return x;
    return father[x] = find(father[x]);
}
void merge(int x,int y)
{
    int a = find(x);
    int b = find(y);
    if (a==b)return;
    if (ranks[a] > ranks[b])father[b] = a;
    else
    {
        father[a] = b;
        if (ranks[a] == ranks[b])ranks[b]++;
    }
}

int main()
{
    int n, m, p;
    scanf("%d%d%d", &n, &m, &p);
    for (int i = 0; i <= n; i++)father[i] = i;
    for (int i = 0; i < m; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        merge(a, b);
    }
    for (int i = 0; i < p; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        if (find(a) == find(b))printf("Yes\n");
        else printf("No\n");
    }

}

 

posted @ 2020-06-28 20:52  Jason66661010  阅读(226)  评论(0编辑  收藏  举报