zoukankan      html  css  js  c++  java
  • 洛谷 P3367 【模板】并查集

     P3367 【模板】并查集

    题目描述

    如题,现在有一个并查集,你需要完成合并和查询操作。

    输入输出格式

    输入格式:

    第一行包含两个整数N、M,表示共有N个元素和M个操作。

    接下来M行,每行包含三个整数Zi、Xi、Yi

    当Zi=1时,将Xi与Yi所在的集合合并

    当Zi=2时,输出Xi与Yi是否在同一集合内,是的话输出Y;否则话输出N

    输出格式:

    如上,对于每一个Zi=2的操作,都有一行输出,每行包含一个大写字母,为Y或者N

    输入输出样例

    输入样例#1:
    4 7
    2 1 2
    1 1 2
    2 1 2
    1 3 4
    2 1 4
    1 2 3
    2 1 4
    输出样例#1:
    N
    Y
    N
    Y
    

    说明

    时空限制:1000ms,128M

    数据规模:

    对于30%的数据,N<=10,M<=20;

    对于70%的数据,N<=100,M<=1000;

    对于100%的数据,N<=10000,M<=200000。

    /*并查集模板题*/
    #include<algorithm>
    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<cmath>
    using namespace std;
    const int mxn=210000;
    int read(){
        int x=0,f=1;char ch=getchar();
        while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();}
        while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();}
        return x*f;
    }
    int n,m;
    int fa[mxn];
    void init()
    {
        for(int i=1;i<=n;i++)
        {
            fa[i]=i;
        }
    }
    int find(int x)
    {
        if (fa[x]==x)
            return x;
        return fa[x]=find(fa[x]);
    }
    int main()
    {
        n=read();m=read();
        init();
        int x,y,z;
        while(m--)
        {
            z=read();x=read();y=read();
            x=find(x);
            y=find(y);
            if(z==1){
                fa[x]=y;
            }
            else{
                if(x==y){
                    printf("Y
    ");
                }
                else printf("N
    ");
            }
        }
        return 0;
    }
  • 相关阅读:
    Fiddler 教程
    Snippet Compiler——代码段编译工具
    HTML5 Audio时代的MIDI音乐文件播放
    sql 数据库 庞大数据量 需要分表
    使用LINQ查询非泛型类型
    找出numpy array数组的最值及其索引
    list的*运算使用过程中遇到的问题
    4.keras实现-->生成式深度学习之用GAN生成图像
    np.repeat 与 np.tile
    pandas中的axis=0,axis=1,傻傻分不清楚
  • 原文地址:https://www.cnblogs.com/xiaoqi7/p/5906376.html
Copyright © 2011-2022 走看看