首页 > 其他 > 详细

luogu P3367 【模板】并查集

时间:2019-05-27 21:20:24      阅读:142      评论:0      收藏:0      [点我收藏+]

 

 

传送门

今天是2019.5.27 距离NOIP2019还有165天

这里是一道并查集模板题

并查集大家都不陌生

 

然而在学习的过程中我猜很多小伙伴

可能都对find(i)和fa[i]的区别产生了疑问

这里我解释一下

就是说find(i)的值一定是节点i的最上层的祖先

而fa(i)则不一定

当每一次合并包含i的子树时find(i)的值是一定变化的

而fa[i]的值只有当你使用了find(i)之后它才会更新

上代码

 

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cctype>
#include<cstdlib>
#include<string>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#define enter puts("")
#define space putchar(‘ ‘)
using namespace std;
typedef long long ll;
ll read()
{
    ll op = 1, ans = 0;
    char ch = getchar();
    while(ch < 0 || ch > 9)
    {
        if(ch == -) op = 0;
        ch = getchar();
    }
    while(ch >= 0 && ch <= 9)
    {
        ans *= 10;
        ans += ch - 0;
        ch = getchar();
    }
    return op ? ans : -ans;
}
void write(ll x)
{
    if(x < 0)
    {
        x = -x;
        putchar(-);
    }
    if(x >= 10) write(x / 10);
    putchar(x % 10 + 0);
}
ll fa[10005], n, m;
ll find(ll x)
{
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}
int main()
{
    n = read(), m = read();
    for(int i = 1;i <= n;i++) fa[i] = i;
    for(int i = 1;i <= m;i++)
    {
        ll a, b, c;
        a = read(), b = read(), c = read();
        if(a == 1)
        {
            int sb = find(b), lj = find(c);
            if(sb != lj) fa[lj] = sb;
        }
        else
        {
            if(find(c) == find(b)) putchar(Y), enter;
            else putchar(N), enter;
        }
    }
    return 0;
}

 

luogu P3367 【模板】并查集

原文:https://www.cnblogs.com/thx666/p/10933348.html

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