Asya And Kittens
prologue
大水题
analysis
我们要维护连通块,题目给的样例解释也很清楚,就是让我们将两个连通块合并。
我们之后只需要用一个链表来维护头尾就好了。
这个过程直接用并查集维护就好了。
code time
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fom(i, a) for(int i=a; i; -- i)
#define foa(i, a, b) for(int i=a; i < b; ++ i)
#define fos(i, a, b) for(int i=a; i <= b; ++ i)
#define fop(i, a, b) for(int i=a; i >= b; -- i)
#define ws putchar(' ')
#define wl putchar('\n')
template <class T> void waw(T x)
{
if(x > 9) waw(x / 10);
putchar(x % 10 ^ 48);
}
template <class T> inline void ww(T x)
{
if(x < 0) x = ~x + 1, putchar('-');
waw(x);
}
template <class T> inline void read(T &res)
{
char ch = getchar(); bool f = 0; res = 0;
for(; !isdigit(ch); ch = getchar()) f |= ch == '-';
for(; isdigit(ch); ch = getchar()) res = (res << 1) + (res << 3) + (ch ^ 48);
res = f ? ~res + 1 : res;
}
const int N = 2e5 + 10;
ll n;
ll p[N], h[N], ne[N], t[N];
inline ll find(ll x) { return (p[x] == x) ? x : p[x] = find(p[x]); }
inline void merge(ll x, ll y)
{
ll a = find(x), b = find(y);
ne[t[a]] = h[b], t[a] = t[b];
p[b] = a;
}
int main()
{
read(n);
fos(i, 1, n) p[i] = h[i] = t[i] = i;
foa(i, 1, n)
{
ll x, y; read(x), read(y);
merge(x, y);
}
ll s = h[find(1)];
fos(i, 1, n) ww(s), ws, s = ne[s];
return 0;
}

浙公网安备 33010602011771号