数字替换

思路

由于每次替换不是永久性替换,因此我们可以考虑逆序去执行操作,这样每次的替换操作就可以当做是一个永久性替换
考虑用 \(f_i\) 表示 \(i\) 被替换后的数字,倒序遍历所有操作然后插入到答案数组即可

CODE

#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
#define ll long long
#define rep(i, a, b) for(int i(a); i <= b; ++ i)
#define dec(i, a, b) for(int i(a); i >= b; -- i)
using namespace std;
const int N = 5e5 + 10;
namespace fast_IO {
    char buf[N], *s, *t;
    char getchar() {
        return (s == t) && (t = (s = buf) + fread(buf, 1, N, stdin)), s == t ? -1 : *s++;
    }
    int read() {
        int num = 0;
        char c;
        while ((c = getchar()) != '-' && c != '+' && (c < '0' || c > '9') && ~c);
        num = c ^ 48;
        while ((c = getchar()) >= '0' && c <= '9')
            num = (num << 1) + (num << 3) + (c ^ 48);
        return num;
    }
}
struct node {
	int op, x, y;
}q[N];
int f[N];
int main() {
	int n = fast_IO::read();
	int m = 0;
	rep(i, 1, n) {
		int op = fast_IO::read(); int x, y;
		if(op & 1) {
			++ m;
			x = fast_IO::read();
		} else {
			x = fast_IO::read(), y = fast_IO::read();
		}
		q[i] = {op, x, y};
	}
	reverse(q + 1, q + n + 1);
	rep(i, 1, N - 1) f[i] = i;
	vector<int> ans(m); int id = 0;
	rep(i, 1, n) {
		int op = q[i].op, x = q[i].x, y = q[i].y;
		if(op & 1) ans[id ++] = f[x];
		else f[x] = f[y];
	}
	reverse(ans.begin(), ans.end());
	for(int x: ans) printf("%d ", x);

	return 0;
}
posted @ 2022-04-10 23:06  ccz9729  阅读(236)  评论(0编辑  收藏  举报