E. Replace the Numbers

· · 题解

维护一个初始为空的队列,执行 q 次操作:

  • 1 x:在数列末尾加一个数字;
  • 2 x y:将队列中所有值为 x 的数的值替换成 y。

输出最终队列。

可以发现值域很小,因此维护 5 \times 10^5 个 set,其中 S_i 表示目前队列中所有值为 i 的元素出现的位置。

对于两种操作:

最后统计答案。若令 \{a\} 表示最终的答案序列,那么若 j \in S_i 则 a_j = i。

#include <bits/stdc++.h>

using namespace std;

const int N = 500010;

int q, n, op, x, y;
set<int> S[N];
int res[N];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    cin >> q;
    while (q -- ) {
        cin >> op >> x;
        if (op == 1) S[x].insert( ++ n);
        else {
            cin >> y;
            if (x == y) continue;
            if (S[x].size() < S[y].size()) {
                for (int i : S[x]) S[y].insert(i);
                S[x].clear();
            }
            else {
                for (int i : S[y]) S[x].insert(i);
                S[y].clear();
                swap(S[x], S[y]);
            }
        }
    }

    for (int i = 1; i < N; ++ i )
        for (int j : S[i])
            res[j] = i;

    for (int i = 1; i <= n; ++ i ) cout << res[i] << ' ';

    return 0;
}