1346:【例4-7】亲戚(relation)

本文详细介绍了并查集的基本概念,提供了并查集的数据结构实现代码,并通过一道具体的题目来展示并查集的应用场景。文章首先定义了并查集的数组表示法,接着给出了查找和合并操作的具体实现,最后通过一道题目演示了如何使用并查集解决连接性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

并查集的模板题:

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 2e4+5;
int fa[maxn];
int find(int x)
{
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}
void unite(int x, int y)
{
    int x1 = find(x);
    int y1 = find(y);
    if (x1 != y1)fa[x1] = y1;
}
int main()
{
    int n, m, x, y;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i)fa[i] = i;
    while (m--)
    {
        scanf("%d%d", &x, &y);
        unite(x, y);
    }
    scanf("%d", &m);
    while (m--)
    {
        scanf("%d%d", &x, &y);
        if (find(x) == find(y))printf("Yes\n");
        else printf("No\n");
    }
}

 

转载于:https://www.cnblogs.com/ALINGMAOMAO/p/10088755.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值