【一次做cf,用递归版的超时了,非递归版的就ac了】
递归版
#include <bits/stdc++.h>
using namespace std;
const int N=1e3;
int fa[N];
int find(int x){
return fa[x] = (fa[x]==x?x:find(fa[x]));
}
void Union(int x, int y){
int fx = find(x);
int fy = find(y);
fa[fy] = fx;
} 非递归版
#include <bits/stdc++.h>
using namespace std;
const int N=1e3;
int fa[N];
int find(int x)
{
int i=x, r=x, j;
while(fa[r]!=r) r=fa[r];
while(fa[i]!=r)
{
j=fa[i];
fa[i]=r;
i=j;
}
return r;
}
void Union(int a,int b)
{
int fx=find(a);
int fy=find(b);
if(fx!=fy) fa[fx]=fy;
}

本文分享了一次Codeforces竞赛中使用并查集的经验,对比了递归与非递归两种实现方式。非递归版本在效率上明显优于递归版本,避免了栈溢出等问题。文中提供了两种实现的具体代码。
1861

被折叠的 条评论
为什么被折叠?



