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
如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!