https://codeforces.com/contest/1131/problem/F

题解:并查集+路径压缩+DFS+树

/*
*@Author:   STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=150000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,q;
int ans,cnt,flag,temp;
int vis[N];
int pre[N];
char str;
vector<int>G[N];
int find(int x){
    if(pre[x]==x)
        return x;
    return pre[x]=find(pre[x]);
}
void add(int a,int b){
    int rx=find(a);
    int ry=find(b);
    if(rx!=ry)
        pre[rx]=ry,G[ry].push_back(rx);
}
void dfs(int rt){
    printf("%d ",rt);
    int sz=G[rt].size();
    if(sz==0)
        return;
    for(int i=0;i<sz;i++){
        int k=G[rt][i];
        if(vis[k]==0){
            vis[k]=1;
            dfs(k);
            vis[k]=0;
        }
    }
}
int main()
{
#ifdef DEBUG
	freopen("input.in", "r", stdin);
	//freopen("output.out", "w", stdout);
#endif
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        pre[i]=i;
    for(int i=1;i<n;i++){
        scanf("%d%d",&m,&k);
        add(m,k);
    }
    for(int i=1;i<=n;i++){
        if(pre[i]==i){
            vis[i]=1;
            dfs(i);
            vis[i]=0;
            break;
        }
    }
    //cout << "Hello world!" << endl;
    return 0;
}