/*闲着没事X2*/
写了个并查集
//适配作用:洛谷P3367 【模板】并查集
//https://www.luogu.org/problemnew/show/P3367
上代码:
#include< bits/stdc++.h>
using namespace std;
struct node{
int father,depth;//depth是深度,从1开始,father…字面意思
};
int n,m;
node a[100001];
int find(int x)//查找根函数
{
if(a[x].father==x)
return x;
a[x].father=find(a[x].father);//路径压缩
a[x].depth=a[a[x].father].depth;
return a[x].father;
}
void merge(int x,int y)//合并操作
{
int p=find(x),q=find(y);
a[x].father=p;
a[y].father=q;//路径压缩X2(虽然没什么用)
if(p==q)
{
return;
}
if(a[x].depth>a[y].depth)//比较高度,避免退化情况
{
a[a[y].father].father=x;
}
else if(a[y].depth>a[x].depth)
{
a[a[x].father].father=y;
}
else//对相同进行特判
{
a[a[y].father].father=x;
find(y);
a[x].depth++;
a[y].depth++;
}
}
void init()//初始化
{
for(int i=1;i<=n;i++)
{
a[i].father=i;
a[i].depth=1;
}
}
int main()//此并查集
{
scanf(“%d %d”,&n,&m);//n为顶点数,m为操作数
init();//初始化(很重要)
for(int i=1;i<=m;i++)
{
int l,p,q;
scanf(“%d”,&l);
scanf(“%d %d”,&p,&q);
if(l==1)
merge(p,q);
else
{
int x=find(p),y=find(q);
if(x==y)printf(“Y\n”);
else printf(“N\n”);
}
}
}