当前位置: 首页 > news >正文

P3367 【模板】并查集

题目链接:点击进入
题目
思路
代码(路径压缩)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;

int n,m,fa[maxn];

int find(int x)
{
    if(x==fa[x]) return x;
    else return fa[x]=find(fa[x]);
}

int unions(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
    {
        fa[fx]=fy;
        return 0;
    }
    else return 1;
}


int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++) fa[i]=i; 
	for(int i=1;i<=m;i++)
	{
		int op,x,y;
		cin>>op>>x>>y;
		if(op==1) 
			unions(x, y);
		else 
		{ 
			int fx=find(x),fy=find(y); 
			if(fx==fy) cout<<"Y"<<endl; 
			else cout<<"N"<<endl; 
		}
	}
	return 0; 
} 
代码(路径压缩+按秩合并)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;

int n,m,fa[maxn],size[maxn];

int find(int x)
{
    if(x==fa[x]) return x;
    else return fa[x]=find(fa[x]);
}

int unions(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
    {
    	if(size[fy]<size[fx]) 
			swap(fx, fy); 
		size[fy]+=size[fx];
		fa[fx]=fy; 
        return 0;
    }
    else return 1;
}


int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++) fa[i]=i,size[i]=1; 
	for(int i=1;i<=m;i++)
	{
		int op,x,y;
		cin>>op>>x>>y;
		if(op==1) 
			unions(x, y);
		else 
		{ 
			int fx=find(x),fy=find(y); 
			if(fx==fy) cout<<"Y"<<endl; 
			else cout<<"N"<<endl; 
		}
	}
	return 0; 
} 
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.dtcms.com/a/126040.html

相关文章:

  • 【局域网】
  • 记 etcd 无法在docker-compose.yml启动后无法映射数据库目录的问题
  • 视觉目标检测大模型GAIA
  • HTTP:三.HTTP报文
  • Win11系统 VMware虚拟机 安装教程
  • mac|使用scrcpy实现无线Android投屏
  • android TabLayout中tabBackground和background的区别
  • SSRF打靶总结
  • JS 构造函数实现封装性
  • 从keys到SCAN:Redis批量删除的进化之路
  • BT面板docker搭建excalidraw遇到的问题
  • AI大模型从0到1记录学习 day16
  • 水利水电安全员C证怎么考,报考有什么流程
  • Franka 机器人x Dexterity Gen引领遥操作精细任务新时代
  • 从三围学校项目看:中建海龙智能建造的崛起与突破
  • 安装python -m weditor报错解决方法
  • 7. 解立方根
  • 人工智能在医疗设备中的最新应用案例与技术挑战?
  • 安卓手机怎样开启双WiFi加速
  • 在线教程丨字节开源 InfiniteYou 图像生成框架,实现高保真面部特征迁移
  • 一文全面了解超融合产品:科技融合的新力量
  • 5分钟读懂ArgoCD:在Kubernetes中实现持续部署
  • 怎样才不算干扰球·棒球1号位
  • feign 使用时可能的问题
  • 国内智能外呼系统市场概况及技术发展趋势
  • [250411] Meta 发布 Llama 4 系列 AI 模型 | Rust 1.86 引入重大语言特性
  • mysql相关面试题
  • Ubuntu虚拟机连不上网
  • 华为华三模拟器解决兼容问题Win11 24H2 现在使用ENSP的问题解决了
  • webrtc pacer模块(一) 平滑处理的实现