LibreOJ #109. 并查集

本文详细介绍了并查集算法在解决图论问题中的应用。通过LibreOJ#109题目的示例代码,展示了如何实现并查集的基本操作如查找、合并等,并解释了这些操作在解决联通性问题上的作用。

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

二次联通门 : LibreOJ #109. 并查集

 

 

 

 

/*
    LibreOJ #109. 并查集

    并查集 
*/
#include <cstdio>

#define Max 4000090
#define Mod 998244353

void read (int &now)
{
    now = 0;
    register char word = getchar ();
    while (word < '0' || word > '9')
        word = getchar ();
    while (word >= '0' && word <= '9')
    {
        now = now * 10 + word - '0';
        word = getchar ();
    }
}

int N, M;
int father[Max];

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

inline void Merge (int x, int y)
{
    int now_1 = Find (x);
    int now_2 = Find (y);
    
    if (x != y)
        father[x] = y;
    return ;
}

inline int Query (int x, int y)
{
    return Find (x) == Find (y);
}

int number[Max];

int main (int argc, char *argv[])
{
    read (N);
    read (M);
    
    int x, y, type;
    register int cur = 0;
    for (register int i = 1; i <= N; i ++)
        father[i] = i;
        
    long long Answer = 0;
    for (; M --; )
    {
        read (type);
        read (x);
        read (y);
        x ++;
        y ++;
        if (type == 0)
            Merge (x, y);
        else
            Answer = ((Answer << 1) + Query (x, y)) % Mod;
    }

    
    printf ("%lld", Answer);
    return 0;
}

 

转载于:https://www.cnblogs.com/ZlycerQan/p/7076249.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值