110 并查集
作者:互联网
视频链接:
// Luogu P3367 【模板】并查集 ///////路径压缩 #include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N=100010; int n,m,x,y,z; int fa[N]; int find(int x){ if(fa[x]==x) return x; return fa[x]=find(fa[x]); } void unionset(int x,int y){ fa[find(x)]=find(y); } int main(){ cin>>n>>m; for(int i=1;i<=n;i++) fa[i]=i; while(m --){ cin>>z>>x>>y; if(z==1) unionset(x,y); else{ x=find(x),y=find(y); if(x==y) puts("Y"); else puts("N"); } } return 0; } ///////路径压缩 + 按秩合并 #include <iostream> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int N=100010; int n,m,x,y,z; int fa[N]; int find(int x){ if(fa[x]==x) return x; return fa[x]=find(fa[x]); } //记录并初始化子树的大小为1 vector<int>siz(N,1); void unionset(int x,int y){ x=find(x),y=find(y); if(x==y)return; if(siz[x]>siz[y])swap(x,y); fa[x]=y; siz[y]+=siz[x]; } int main(){ cin>>n>>m; for(int i=1;i<=n;i++) fa[i]=i; while(m --){ cin>>z>>x>>y; if(z==1) unionset(x,y); else{ x=find(x),y=find(y); if(x==y) puts("Y"); else puts("N"); } } return 0; }
标签:return,puts,int,查集,fa,110,include,find 来源: https://www.cnblogs.com/dx123/p/16319836.html