# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1083800 | ZeroCool | 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;
#define ar array
#define ll long long
#define ld long double
vector<ar<int, int>> ans, xy, swaps;
bool check(vector<int> p, int m, int n) {
int s = 0;
vector<int> e = p;
vector<int> co(n, 0);
for (int i = 0; i < n; i++) co[p[i]] = i;
for (int i = 0; i < m; i++) swap(p[xy[i][0]], p[xy[i][1]]);
for (int i = 0; i < n; i++) {
if (p[i] == i) continue;
while(p[i] != i) {
int j = p[i];
swaps.push_back({p[i], p[j]});
swap(p[i], p[j]);
s++;
}
}
if (swaps.size() > m)return 0;
while(swaps.size() < m) swaps.push_back({0, 0});
for (int i = 0; i < m; i++) {
swap(co[e[xy[i][0]]], co[e[xy[i][1]]]);
swap(e[xy[i][0]], e[xy[i][1]]);
auto [x, y] = swaps[i];
swaps[i] = {co[x], co[y]};
swap(e[co[x]], e[co[y]]);
swap(co[x], co[y]);
}
return s <= m;
}
int findSwapPairs(int n, int A[], int m, int X[], int Y[], int P[], int Q[]) {
vector<int> p(n);
for (int i = 0; i < n; i++) p[i] = A[i];
for (int i = 0; i < m; i++) xy.push_back({X[i], Y[i]});
int l = 0, r = m - 1;
while(l <= r) {
int m = (l + r)/2;
swaps.clear();
if(check(p, m, n)){
r = m - 1;
ans = swaps;
}else l = m + 1;
}
for (int i = 0; i < ans.size(); i++) {
P[i] = ans[i][0];
Q[i] = ans[i][1];
}
return ans.size();
}