並查集的主要操作有
1-合併兩個不相交集合
2-判斷兩個元素是否屬於同一個集合
貼別鳴謝德翔同學提供該算法模板!
#include <iostream>
#include <map>
using namespace std;
int father[1000];
int search_father(int tar) //查
{
int result=tar;
while(result!=father[result]) //是否根節點
{
result=father[result]; //不是,建立根節點
}
return result; //是,直接返回
}
void combine_tree(int a,int b) //並
{
int fx=search_father(a);
int fy=search_father(b);
if(fx!=fy)
father[fx]=fy;//合併父節點
}
int main()
{
for(int i=0;i<10;i++)
{
father[i]=i;
}
for(int i=0;i<10;i++)
{
cout<<father[i]<<" ";
}
cout<<endl;
int a,b;
cin>>a>>b;
combine_tree(a,b);
for(int i=0;i<10;i++)
{
cout<<father[i]<<" ";
}
cout<<endl;
return 0;
}