zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Java动态绑定和静态绑定-多态
    Java方法内联
    Java反射机制及原理
    Jvm-类加载机制
    Zookeeper 源码解析-环境准备
    SpringMvc源码解析
    Java虚拟机的意义
    起跑线
    js动态生成html,onclick事件失效解决方法
    虚拟机能ping通,但是telnet某个端口却不行
  • 原文地址:https://www.cnblogs.com/thx666/p/10933348.html
Copyright © 2011-2022 走看看