# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
288420 | Kastanda | Sorting (IOI15_sorting) | C++11 | 206 ms | 17832 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.
// M
#include<bits/stdc++.h>
#include "sorting.h"
using namespace std;
const int N = 200005 * 3;
int n, m, S[N], X[N], Y[N];
int A[N], M[N], Rev[N];
inline bool Solve(int md)
{
for (int i = 0; i < n; i ++)
A[i] = S[i], M[i] = 0;
for (int i = 0; i < md; i ++)
swap(A[X[i]], A[Y[i]]);
int Cnt = 0;
for (int i = 0; i < n; i ++)
if (!M[i])
{
int nw = i;
while (!M[nw])
M[nw] = 1, nw = A[nw];
Cnt ++;
}
Cnt = n - Cnt;
return Cnt <= md;
}
int findSwapPairs(int _n, int _S[], int _m, int _X[], int _Y[], int P[], int Q[])
{
n = _n; m = _m;
for (int i = 0; i < n; i ++)
S[i] = _S[i];
for (int i = 0; i < m; i ++)
X[i] = _X[i], Y[i] = _Y[i];
{
bool fail = 0;
for (int i = 1; i < n; i ++)
if (S[i] < S[i - 1])
fail = 1;
if (!fail)
return 0;
}
int le = 0, ri = m, md;
while (ri - le > 1)
{
md = (le + ri) >> 1;
if (Solve(md))
ri = md;
else
le = md;
}
assert(Solve(ri));
for (int i = 0; i < n; i ++)
A[i] = S[i], M[i] = 0;
for (int i = 0; i < ri; i ++)
swap(A[X[i]], A[Y[i]]);
vector < pair < int , int > > E;
for (int i = 0; i < n; i ++)
if (!M[i])
{
int nw = i;
vector < int > vec;
while (!M[nw])
{
vec.push_back(nw);
M[nw] = 1;
nw = A[nw];
}
reverse(vec.begin(), vec.end());
for (int j = 1; j < (int)vec.size(); j ++)
E.push_back(make_pair(vec[j - 1], vec[j]));
}
assert(E.size() <= ri);
for (int i = 0; i < n; i ++)
A[i] = S[i];
for (int i = 0; i < n; i ++)
Rev[A[i]] = i;
for (int i = 0; i < ri; i ++)
{
swap(A[X[i]], A[Y[i]]);
swap(Rev[A[X[i]]], Rev[A[Y[i]]]);
if (!E.size())
{
P[i] = Q[i] = 0;
continue;
}
int a = E.back().first;
int b = E.back().second;
E.pop_back();
int ra = Rev[a];
int rb = Rev[b];
P[i] = ra;
Q[i] = rb;
swap(A[ra], A[rb]);
swap(Rev[A[ra]], Rev[A[rb]]);
}
return ri;
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |