D - Inverse and Swap Editorial by sounansya


C++ なら vector 同士の swap が \(O(1)\) 時間でできるので、swap もそのまま問題文通りに行えば良いです。

実装例(C++)

#include <bits/stdc++.h>
using namespace std;
int main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	int n, query;
	cin >> n >> query;
	vector<int> p(n), q(n);
	for (int i = 0; i < n; i++) {
		cin >> p[i];
		p[i]--;
		q[p[i]] = i;
	}
	while (query--) {
		int ty;
		cin >> ty;
		if (ty == 1) {
			int x, y;
			cin >> x >> y;
			x--, y--;
			swap(p[x], p[y]);
			swap(q[p[x]], q[p[y]]);
		} else {
			swap(p, q);
		}
	}
	for (int i = 0; i < n; i++) cout << p[i] + 1 << " \n"[i + 1 == n];
}

posted:
last update: