并查集 5-30 tree ------错误方法

来源:互联网 发布:中国网络发展的评价 编辑:程序博客网 时间:2024/05/16 05:39
#include <iostream>
using namespace std;
int fa[100000];// father

int f_u(int x)
{
int root=x;
while(fa[root]!=root) root=fa[root];
while(fa[x]!=x)
{
int y=fa[x];
fa[x]=root;
x=y; 
}
return root;
}

int main()
{
int n,m;
cin>>n>>m;
int x,y;
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<=m;i++)
{
cin>>x>>y;
int fx=f_u(x);
int fy=f_u(y); 
if(fx!=fy) fa[fx]=fy;
}
for(int i=1;i<=n;i++) f_u(i);  //不知道为什么要多找一次
for(int i=1;i<=n;i++)
cout<<"i="<<i<<" fa="<<fa[i]<<endl;
return 0;
}
2 0