【一次做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;
}