# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
745656 | Dan4Life | Sorting (IOI15_sorting) | C++17 | 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;
const int mxN = (int)2e5+10;
int n, a[mxN], t[mxN], x[mxN], y[mxN], pos[mxN], vis[mxN];
void swp(int i, int j){ swap(pos[a[i]],pos[a[j]]), swap(a[i],a[j]); }
int chk(int m, int P[], int Q[]){
for(int i = 0; i < n; i++)
a[i] = t[i], vis[i]=0, pos[a[i]] = i;
for(int i = 0; i < m; i++)
swp(x[i],y[i]), P[i]=Q[i]=0;
int tot = 0;
for(int i = 0; i < n; i++){
if(vis[i]) continue;
vector<int> v; v.clear(); int j = i;
while(!vis[j]) vis[j]=1, v.push_back(j), j = a[j];
int s = (int)v.size();
for(j = 0; j < s-1; tot++, j++){
P[tot] = pos[a[v[j]]];
Q[tot] = pos[a[v[j+1]]];
swp(pos[a[v[j]]],pos[a[v[j+1]]]);
}
}
return (is_sorted(a,a+n) and tot<=m)?m:mxN;
}
int findSwapPairs(int N, int A[], int m, int X[], int Y[], int P[], int Q[]) {
n = N;
for(int i = 0; i < n; i++){
a[i] = t[i] = A[i];
x[i] = X[i], y[i] = Y[i];
}
int l = 0, r = n-1;
while(l<r){
int mid = (l+r)/2;
if(chk(mid,a,P,Q)<=mid) r=mid;
else l=mid+1;
}
int ans = chk(l,P,Q);
return ans;
}