#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <queue>
#define MAXN 100010
#define inf 0x3f3f3f3f
using namespace std;
int uset[MAXN];
int deep[MAXN];//深度
void init(){
for(int i = 0; i < MAXN; ++i){
uset[i] = i;
}
memset(deep,0,sizeof(deep));
}
int found(int x){
return x==uset[x]?x:uset[x] = found(uset[x]);
}
int main()
{
int n,m;
int x,y;
while(~scanf("%d",&n)){
init();
scanf("%d",&m);
while(m--){
scanf("%d%d",&x,&y);
int xx = found(x);
int yy = found(y);
if(xx != yy){
uset[xx] = yy;
/*加个深度优化
if(deep[xx] > deep[yy]){
uset[y] = x;
}
else{
uset[x] = y;
if(deep[xx] == deep[yy]){
++deep[yy];
}
}
*/
}
}
for(int i = 1; i <= n; ++i){
x = found(i);
cout<<x<<endl;
}
}
return 0;
}
并查集
最新推荐文章于 2024-07-29 20:58:50 发布