并查集
例题 洛谷3367
题目描述
如题,现在有一个并查集,你需要完成合并和查询操作。
输入格式
第一行包含两个正整数N、M,分别表示查询的范围和查询的个数。
接下来M行每行包含一个不小于1且不大于N的整数,即询问该数是否为质数。
输出格式
输出包含M行,每行为Yes或No,即依次为每一个询问的结果。
输入输出样例
输入
4 7
2 1 2
1 1 2
2 1 2
1 3 4
2 1 4
1 2 3
2 1 4
输出
N
Y
N
Y
说明/提示
时空限制:1000ms,128M
数据规模:
对于30%的数据,N<=10,M<=20;
对于70%的数据,N<=100,M<=1000;
对于100%的数据,N<=10000,M<=200000。
代码/模板
//https://www.luogu.org/problem/P3367
#include<cmath>
#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
#define LL long long
#define MOD 10000000
inline LL read()
{
LL x=0,w=1;
char ch=0;
while(ch<'0'||ch>'9')
{
if(ch=='-')
w=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return w*x;
}
int n,m,z,x,y,fa[10005];
int find(int xx)//寻找xx的根(路径压缩版)
{
int r=xx;
while(fa[r]!=r)//找到xx的根,用r记录
{
r=fa[r];
}
int now=xx,pr;//now代表当前节点 pr代表当前节点的上一级
while(now!=r)//将节点x以及x到根节点中间所有的点进行路径压缩
{
pr=fa[now];//记录当前节点的上一级
fa[now]=r;//路径压缩
now=pr;//将当前节点上跳为上一级,直到跳至根节点
}
return r;
}
void un(int xx,int yy)//合并两个节点
{
int tx=find(xx);
int ty=find(yy);
fa[tx]=ty;
}
bool ifin(int xx,int yy)//判断两个点是否在一个集合中
{
return find(xx)==find(yy);
}
int main()
{
n=read();
m=read();
for(register int i=1;i<=n;i++)
{
fa[i]=i;
}
for(register int i=1;i<=m;i++)
{
z=read();
x=read();
y=read();
if(z==1)
{
un(x,y);
}
else
{
if(ifin(x,y))
{
cout<<"Y"<<endl;
}
else
{
cout<<"N"<<endl;
}
}
}
return 0;
}