题目
思路
代码(路径压缩)
#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;
}