Copyright: blogger original, welcome to reprint. Please indicate the source https://blog.csdn.net/baidu_41248654/article/details/78819395
Topic links: https://www.luogu.org/problemnew/show/3367
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,x,y,z,fa[200010];
int get(int a) //存根节点,fa[a]是a的根节点
{
if(fa[a]==a)
return a;
else return fa[a]=get(fa[a]);//加速,a以上的点
}
int main()
{
int fxx,fxy;
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
fa[i]=i;
for(int i=1; i<=m; i++)
{
scanf("%d%d%d",&z,&x,&y);
fxx=get(x);
fxy=get(y);
if(z==1)
{
fa[fxx]=fxy;//合并a和b所在的集合
}
else
{
if(fxx==fxy)//a和b在一个集合中
printf("Y\n");
else
printf("N\n");
}
}
return 0;
}
Also called disjoint-set data structures disjoint sets.
The development of this algorithm has experienced more than a decade, in which Robert E.Tarjan made a great contribution. Previously, John E.Hoperoft and Jeffrey D.Ullman also done a lot of analysis.
Disjoint-set by one-dimensional array to achieve, its essence is to maintain a forest.
Slightly slightly