#include <iostream>
#define maxn 1005
using namespace std;
int fa[maxn];
void init()
{
for(int i=1;i<maxn;++i)
{
fa[i]=i;
}
}
int find_ancestor(int x)
{
if(fa[x]==x)
{
return x;
}
return fa[x]=find_ancestor(fa[x]);//用fa[x]=方式,压缩了路径
}
void and_union(int x,int y)
{
int fx=find_ancestor(x),fy=find_ancestor(y);
if(fx!=fy)
{
fa[fx]=fy;
}
}
int main()
{
init();//先进行初始化
cout<<find_ancestor(1)<<endl;
cout<<find_ancestor(3)<<endl;
if(find_ancestor(1)==find_ancestor(3)){
cout<<"同一个祖先,即位于同一个集合"<<endl;
}else{
cout<<"不在同一个集合"<<endl;
}
and_union(1,3);
cout<<find_ancestor(1)<<endl;
cout<<find_ancestor(3)<<endl;
if(find_ancestor(1)==find_ancestor(3)){
cout<<"同一个祖先,即位于同一个集合"<<endl;
}else{
cout<<"不在同一个集合"<<endl;
}
return 0;
}