洛谷P3367 【模板】并查集

一、题目描述

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

二、输入格式:

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

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

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

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

三、输出格式:

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

四、题解

洛谷有很多模板题,掌握模板题很重要,对于算法来说,如果你连算法的模板都写不出来,又怎么去解题吗?

首先我们先来了解一下什么是并查集?

4.1、并查集

并查集是一种用于分离集合操作的抽象数据类型,这是从某本书上面找的,是的,看着就很抽象。

简单来说,并查集就是对一个集合里面的元素进行某些元素的合并,然后需要在这些元素里面查找某几个元素是否在同一个集合里面,大概就是这样。

那么我们来说说并查集常用到的两个操作:合并,查找。

4.1.1、 合并

现在数组arr中有6个元素,分别是1、2、3、4、5、6,我们来对这些数据进行合并:
在这里插入图片描述
合并1和2

在这里插入图片描述
合并3和4
在这里插入图片描述
合并3和5
在这里插入图片描述
并查集就是通过这样的合并,来将元素合并在同一个集合中。

合并操作代码如下
void unions(int y1,int y2){
    father[y2] = y1;
}

4.1.2、查找

现在我们要在已经合并后的大集合中查找某几个元素

查找4,5
在这里插入图片描述
我们在arr集合中查找元素4和元素5,判断他们是否在同一个集合中,经查找后发现,他们的父结点都是3,所以他们在同一阵营。

查找2,4
在这里插入图片描述
我们可以发现元素2的父结点是1,元素4的父结点的3,1和3不在同一集合,所以2和4也就不在同一集合了。

查找操作代码如下
int find(int x){
    while(father[x] != x){
        x = father[x];
    }
    return x;
}

有了上面这些知识后,我们来解这道题就很简单了,我就直接上代码了

五、代码实现

#include <iostream>
using namespace std;
const int maxn1 = 10005;
const int maxn2 = 200005;

int arr[maxn1];
struct node{
    int z;int x;int y;
}oper[maxn2];

int find(int root){
    int son = root;
    while(root != arr[root]){
        root = arr[root];
    }
    while(son != root){
        int temp = arr[son];
        arr[son] = root;
        son = temp;
    }
    return root;
}

void unions(int root1, int root2){
    int x = find(root1);
    int y = find(root2);
    if(x != y){
        arr[x] = y;
    }
}

bool judge(int root1, int root2){
    bool flag = false;
    int x = find(root1);
    int y = find(root2);
    if(x == y){
        flag = true;
    }
    return flag;
}

int main(){
    int n,m;
    cin >> n >> m;
    for(int i = 1; i <= n; i ++){
        arr[i] = i;
    }

    for(int i = 1; i <= m; i ++){
        cin >> oper[i].z >> oper[i].x >> oper[i].y;
    }
    bool flag = false;
    for(int i = 1; i <= m; i ++){
        if(oper[i].z == 2){
            flag = judge(oper[i].x,oper[i].y);
            if(flag){
                cout << "Y" << endl;
            }else{
                cout << "N" << endl;
            }
        }else{
            unions(oper[i].x,oper[i].y);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/m0_37550202/article/details/88384146