codeforces #541 F Asya And Kittens(并查集+输出路径)
Asya loves animals very much. Recently, she purchased nn kittens, enumerated them from 11 and nn and then put them into the cage. The cage consists of one row of nn cells, enumerated with integers from 11 to nn from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were n−1n−1 partitions originally. Initially, each cell contained exactly one kitten with some number.
Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day ii, Asya:
- Noticed, that the kittens xixi and yiyi, located in neighboring cells want to play together.
- Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells.
Since Asya has never putted partitions back, after n−1n−1 days the cage contained a single cell, having all kittens.
For every day, Asya remembers numbers of kittens xixi and yiyi, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into nn cells.
The first line contains a single integer nn (2≤n≤1500002≤n≤150000) — the number of kittens.
Each of the following n−1n−1 lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi) — indices of kittens, which got together due to the border removal on the corresponding day.
It's guaranteed, that the kittens xixi and yiyi were in the different cells before this day.
For every cell from 11 to nn print a single integer — the index of the kitten from 11 to nn, who was originally in it.
All printed integers must be distinct.
It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them.
#include <cstdio> #include <map> #include <iostream> #include<cstring> #include<bits/stdc++.h> #define ll long long int #define M 6 using namespace std; inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;} int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1}; int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1}; const int inf=0x3f3f3f3f; const ll mod=1e9+7; int f[200000],n; int path[200000],last[200000]; //path记录路径 last记录最后一个数 int find(int x){ if(x!=f[x]) f[x]=find(f[x]); return f[x]; } void join(int x,int y){ int xx=find(x); int yy=find(y); if(xx!=yy) f[yy]=xx; } int main(){ ios::sync_with_stdio(false); cin>>n; for(int i=1;i<=n;i++) f[i]=i,last[i]=i; n--; while(n--){ int x,y; cin>>x>>y; int xx=find(x); int yy=find(y); if(xx==yy) continue; path[last[xx]]=yy; last[xx]=last[yy]; join(x,y); } for(int i=find(1);i;i=path[i]) cout<<i<<" "; return 0; }