代码库·并查集

2 篇文章 0 订阅
1 篇文章 0 订阅
/*闲着没事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”);
}
}
}

P.S:本人是((提高-普及)/2+普及)的小蒟蒻一枚,写的不好的地方请见谅
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值