# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
259149 | IOrtroiii | Sorting (IOI15_sorting) | C++14 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "sorting.h"
#include <bits/stdc++.h>
using namespace std;
int findSwapPairs(int N, int S[], int M, int X[], int Y[], int P[], int Q[]) {
auto solve = [&](int mid) -> bool {
vector<int> perm(N);
for (int i = 0; i < N; ++i) {
perm[i] = S[i];
}
for (int i = 0; i < mid; ++i) swap(perm[X[i]], perm[Y[i]]);
vector<int> invp(N);
for (int i = 0; i < N; ++i) invp[perm[i]] = i;
int ans = 0;
for (int i = 0; i < N; ++i) {
if (perm[i] == i) continue;
int j = invp[i];
P[ans] = perm[i];
Q[ans++] = perm[j];
swap(perm[i], perm[j]);
invp[perm[i]] = i;
invp[perm[j]] = j;
}
for (int i = ans; i < mid; ++i) P[i] = Q[i] = 0;
return ans <= mid;
};
int low = 0, high = N;
while (low < high) {
int mid = (low + high) >> 1;
if (solve(mid)) high = mid;
else low = mid + 1;
}
solve(low);
vector<int> perm(N);
for (int i = 0; i < N; ++i) perm[i] = S[i];
vector<int> invp(N);
for (int i = 0; i < low; ++i) {
swap(perm[X[i]], perm[Y[i]]);
invp[perm[X[i]]] = X[i];
invp[perm[Y[i]]] = Y[i];
P[i] = invp[P[i]];
Q[i] = invp[Q[i]];
swap(perm[P[i]], perm[Q[i]]);
invp[perm[P[i]] = P[i];
invp[perm[Q[i]] = Q[i];
}
return low;
}