P3367 【模板】并查集

P3367 【模板】并查集

题目背景

自 2025 年 1 月 21 日,本题测试数据范围更新,详见:https://www.luogu.com.cn/discuss/1045596

这意味着现存题解的代码可能无法通过本题,管理组将会在 2025 年 2 月处理。

题目描述

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

输入格式

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

接下来 \(M\) 行,每行包含三个整数 \(Z_i,X_i,Y_i\)

\(Z_i=1\) 时,将 \(X_i\)\(Y_i\) 所在的集合合并。

\(Z_i=2\) 时,输出 \(X_i\)\(Y_i\) 是否在同一集合内,是的输出
Y ;否则输出 N

输出格式

对于每一个 \(Z_i=2\) 的操作,都有一行输出,每行包含一个大写字母,为 Y 或者 N

输入输出样例 #1

输入 #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

说明/提示

对于 \(15\%\) 的数据,\(N \le 10\)\(M \le 20\)

对于 \(35\%\) 的数据,\(N \le 100\)\(M \le 10^3\)

对于 \(50\%\) 的数据,\(1\le N \le 10^4\)\(1\le M \le 2\times 10^5\)

对于 \(100\%\) 的数据,\(1\le N\le 2\times 10^5\)\(1\le M\le 10^6\)\(1 \le X_i, Y_i \le N\)\(Z_i \in \{ 1, 2 \}\)

#include<iostream>
using namespace std;
const int N=2*1e5+5;
int f[N];
int n,m;
void init(){
    for(int i=1;i<=n;i++)f[i]=i;
}
int find(int x){
    if(x!=f[x])return f[x]=find(f[x]);
    return f[x];
}
void merge(int x,int y){
    f[find(x)]=find(y);//查询时顺带压缩路径
}
int main(){
    cin>>n>>m;
    init();
    while(m--){
        int z,x,y;
        cin>>z>>x>>y;
        if(z==1)merge(x,y);
        if(z==2){
            int root1=find(x);
            int root2=find(y);
            if(root1==root2)cout<<"Y"<<endl;
            else cout<<"N"<<endl;
        }
    }
    return 0;
}
posted @ 2025-02-26 20:47  郭轩均  阅读(14)  评论(0)    收藏  举报