大佬们,p1551关系遍历为啥最后的结果是5 5 4 4 4 6
前五个都有关系不应该为相同的数吗(就是输出同一祖先)
代码奉上 跪求题解!!
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
int n=0,m=0,x=0,y=0;
int f[maxn];
int fd(int x){
if(f[x]!=x) f[x]=fd(f[x]);
return f[x];
}
void hb(int x,int y){
int r1=fd(x);
int r2=fd(y);
f[r1]=r2;
}
void read(){
cin>>n;
cin>>m;
for(int i=1;i<=n;++i) f[i]=i;
for(int i=1;i<=m;++i){
cin>>x>>y;
hb(x,y);
for(int i=1;i<=n;++i){
cout<<f[i]<<" ";
}
cout<<endl;
}
}
int main(){
read();
return 0;
}