zoukankan      html  css  js  c++  java
  • 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<iostream>
    using namespace std;
    const int inf=10010;
    int a[inf];
    int find(int x)
    {
    if(x!=a[x])
    return a[x]=find(a[x]);//路径压缩 每次回溯的时候都让经过的节点指向根节点就可以了。
    else
    return x;
    }
    int main()
    {
    int n,m,z,x,y;
    cin>>n>>m;
    for(int i=0;i<=n;i++)
    a[i]=i;
    while(m--)
    {
    cin>>z>>x>>y;
    if(z==1)
    {
    int x1=find(x);
    int y1=find(y);
    if(x1!=y1)
    a[y1]=x1;
    }
    else if(z==2)
    {
    int x1=find(x);
    int y1=find(y);
    if(x1!=y1)
    printf("N ");
    else
    printf("Y ");
    }
    }
    return 0;
    }

    如果你够坚强够勇敢,你就能驾驭他们
  • 相关阅读:
    codeforces C. Cows and Sequence 解题报告
    codeforces A. Point on Spiral 解题报告
    codeforces C. New Year Ratings Change 解题报告
    codeforces A. Fox and Box Accumulation 解题报告
    codeforces B. Multitasking 解题报告
    git命令使用
    shell简单使用
    知识束缚
    php 调用系统命令
    数据传输方式(前端与后台 ,后台与后台)
  • 原文地址:https://www.cnblogs.com/liuzhaojun/p/11268040.html
Copyright © 2011-2022 走看看