zoukankan      html  css  js  c++  java
  • [模板] 并查集

    #include <iostream>
    using namespace std;
    
    const int MAXN = 1e4 + 10;
    
    int arr[MAXN];
    
    int N, M;
    
    void init(int N)    //初始化根节点为自己
    {
        for(int i = 1; i <= N; i++)
            arr[i] = i;
    }
    
    int findfather(int x)       //寻父节点(根节点)
    {
        if(arr[x] == x)
            return x;
        return arr[x] = findfather(arr[x]);     //寻找过程中路径压缩 全部更新为根节点 提升查询速度
    }
    
    bool checkin(int x, int y)      //查是否在一个集合中
    {
        x = findfather(x);
        y = findfather(y);
    
        if(x == y)
            return true;
    
        return false;
    }
    
    void join(int x, int y)     //若不在一个集合中 更新结点
    {
        x = findfather(x), y = findfather(y);
        if(x != y)
            arr[x] = y;
    }
    
    int main()
    {
        ios::sync_with_stdio(false);
    
        cin>>N>>M;
    
        init(N);
    
        int z, x, y;
    
        while(M--)
        {
            cin>>z>>x>>y;
    
            if(z == 1)
            {
                join(x, y);
            }
    
            else 
            {
                if(checkin(x, y))
                    cout<<"Y"<<endl;
                
                else
                    cout<<"N"<<endl;
            }
        }
    
        return 0;
    }
  • 相关阅读:
    rocketMQ配置事故
    微信网页授权问题记录
    记一次Spring配置事故
    文件转换
    Java对象空间分配流程
    mysql(六)索引的数据结构
    mysql(五)查询缓存
    mysql(四)log
    从项目中加载文件
    cookie
  • 原文地址:https://www.cnblogs.com/zeolim/p/12270556.html
Copyright © 2011-2022 走看看