luogu P3367 【模板】并查集

 

 

传送门

今天是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;
}

 

posted @ 2019-05-27 21:14  thx666  阅读(150)  评论(2编辑  收藏  举报