并查集

并查集

例题 洛谷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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值