C01【模板】并查集
//并查集 路径压缩 #include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N=10005; int n,m,x,y,z; int pa[N]; int find(int x){ if(pa[x]==x) return x; return pa[x]=find(pa[x]); } void unset(int x,int y){ pa[find(x)]=find(y); } int main(){ cin>>n>>m; for(int i=1;i<=n;i++) pa[i]=i; while(m --){ cin>>z>>x>>y; if(z==1) unset(x,y); else{ if(find(x)==find(y)) puts("Y"); else puts("N"); } } }
//并查集 路径压缩+按秩合并 #include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N=10005; int n,m,x,y,z; int pa[N],siz[N]; //子树大小 int find(int x){ if(pa[x]!=x)pa[x]=find(pa[x]); return pa[x]; } void unset(int x,int y){ x=find(x),y=find(y); if(x==y)return; if(siz[x]<siz[y])swap(x,y); pa[y]=x; siz[x]+=siz[y]; } int main(){ cin>>n>>m; for(int i=1;i<=n;i++) pa[i]=i,siz[i]=1; while(m --){ cin>>z>>x>>y; if(z==1) unset(x,y); else{ if(find(x)==find(y))puts("Y"); else puts("N"); } } }
P1551 亲戚 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P2078 朋友 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P2814 家谱 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1536 村村通 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1111 修复公路 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1195 口袋的天空 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1455 搭配购买 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1396 营救 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1991 无线通讯网 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P4047 [JSOI2010] 部落划分 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1967 [NOIP2013 提高组] 货车运输 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!