Codeforces #541 (Div2) - F. Asya And Kittens(并查集+链表)

时间:2024-01-06 16:35:08

Problem   Codeforces #541 (Div2) - F. Asya And Kittens

Time Limit: 2000 mSec

Codeforces #541 (Div2) - F. Asya And Kittens(并查集+链表)Problem Description

Codeforces #541 (Div2) - F. Asya And Kittens(并查集+链表)

Input

The first line contains a single integer nn (2≤n≤150000) — the number of kittens.

Each of the following n−1lines contains integers xi and yi (1≤xi,yi≤n, xi≠yi) — indices of kittens, which got together due to the border removal on the corresponding day.

It's guaranteed, that the kittens xi and yi were in the different cells before this day.

Codeforces #541 (Div2) - F. Asya And Kittens(并查集+链表)Output

For every cell from 1 to n print a single integer — the index of the kitten from 1 to n, 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.

Codeforces #541 (Div2) - F. Asya And Kittens(并查集+链表)Sample Input

5
1 4
2 5
3 1
4 5

Codeforces #541 (Div2) - F. Asya And Kittens(并查集+链表)Sample Output

3 1 4 2 5

题解:并查集+链表,始终把y所在的集合加到x所在集合的右边,让每个集合的根始终保持在最左边,维护一下每个集合最左边元素,链表连一连即可,这种题拼的就是手速。

 #include <bits/stdc++.h>

 using namespace std;

 #define REP(i, n) for (int i = 1; i <= (n); i++)
#define sqr(x) ((x) * (x)) const int maxn = + ;
const int maxm = + ;
const int maxs = + ; typedef long long LL;
typedef pair<int, int> pii;
typedef pair<double, double> pdd; const LL unit = 1LL;
const int INF = 0x3f3f3f3f;
const LL mod = ;
const double eps = 1e-;
const double inf = 1e15;
const double pi = acos(-1.0); int n;
int fa[maxn], ri[maxn];
int ans[maxn];
int edge[maxn]; int findn(int x)
{
return x == fa[x] ? x : fa[x] = findn(fa[x]);
} void init()
{
for (int i = ; i < maxn; i++)
{
fa[i] = edge[i] = ri[i] = i;
}
} int main()
{
ios::sync_with_stdio(false);
cin.tie();
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
init();
cin >> n;
int x, y;
for (int i = ; i < n - ; i++)
{
cin >> x >> y;
int fx = findn(x), fy = findn(y);
fa[fy] = fx;
ri[edge[fx]] = fy;
edge[fx] = edge[fy];
}
int root = -;
for (int i = ; i <= n; i++)
{
if (findn(i) == i)
{
root = i;
}
}
ans[] = root;
int cnt = ;
for (int i = ri[root]; cnt++; i = ri[i])
{
ans[cnt] = i;
if (cnt == n)
break;
}
for(int i = ; i <= n; i++)
{
cout << ans[i];
if(i != n)
{
cout << " ";
}
else
{
cout << endl;
} }
return ;
}