Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- int main() {
- int n; cin >> n;
- vector<int> p(n);
- for (int &x : p) cin >> x;
- int m; cin >> m;
- vector<int> x(m), y(m);
- for (int i = 0; i < m; ++i) cin >> x[i] >> y[i];
- auto perform = [&p, &x, &y](int k) {
- vector<int> v = p;
- for (int i = 0; i < k; ++i) swap(v[x[i]], v[y[i]]);
- return v;
- };
- auto minMoves = [&n](const vector<int> &v) {
- vector<bool> seen(n);
- int cycles = 0;
- for (int i = 0; i < n; ++i) {
- if (!seen[i]) {
- ++cycles;
- int j = i;
- do {
- seen[j] = true;
- j = v[j];
- } while (j != i);
- }
- }
- return n-cycles;
- };
- int left = -1, right = m+1;
- while (left+1 < right) {
- int k = (left + right) / 2;
- vector<int> v = perform(k);
- if (minMoves(v) <= k) right = k;
- else left = k;
- }
- cout << right << endl;
- auto getMoves = [&n](const vector<int>& v) {
- vector<bool> seen(n);
- vector<pair<int, int>> moves; // by value (not index)
- for (int i = 0; i < n; ++i) {
- if (!seen[i]) {
- int j = i;
- do {
- seen[j] = true;
- if (v[j] != i) moves.emplace_back(v[j], v[v[j]]);
- j = v[j];
- } while (j != i);
- }
- }
- return moves;
- };
- vector<pair<int, int>> moves = getMoves(perform(right)); // by value (not index)
- while ((int)moves.size() < right) moves.emplace_back(0, 0);
- // simulate the moves
- vector<int> where(n);
- for (int i = 0; i < n; ++i) where[p[i]] = i;
- for (int i = 0; i < right; ++i) {
- // perform the forced move
- swap(p[x[i]], p[y[i]]);
- swap(where[p[x[i]]], where[p[y[i]]]);
- // work out what positions correspond to the chosen move
- cout << where[moves[i].first] << ' ' << where[moves[i].second] << endl;
- swap(where[moves[i].first], where[moves[i].second]);
- swap(p[where[moves[i].first]], p[where[moves[i].second]]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement