#include "sorting.h"
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
int findSwapPairs(int N, int SS[], int M, int X[], int Y[], int P[], int Q[]) {
int A[N], pos[N], L[M], R[M], ret = (1<<30), S[N];
int tl = 0, tr = M - 1;
while (tl <= tr) {
int m = tl + tr >> 1;
for (int i = 0; i < N; ++i)
A[i] = i, S[i] = SS[i];
for (int i = m; i >= 0; --i)
swap(A[X[i]], A[Y[i]]);
int bad = 0;
for (int i = 0; i < N; ++i)
if (S[i] != i)
bad++;
int r = -1;
stack<int>s;
for (int j = 0; j < N; ++j)
pos[A[j]] = j, s.push(j);
for (int i = 0; i <= m; ++i) {
P[i] = Q[i] = 0;
if (bad == 0) {
r = i;
break;
}
if (S[X[i]] != X[i])
bad--;
if (S[Y[i]] != Y[i])
bad--;
swap(S[X[i]], S[Y[i]]);
swap(A[X[i]], A[Y[i]]);
if (S[X[i]] != X[i])
bad++;
if (S[Y[i]] != Y[i])
bad++;
if (bad == 0) {
r = i + 1;
break;
}
swap(pos[A[X[i]]], pos[A[Y[i]]]);
while (pos[S[s.top()]] == s.top())
s.pop();
if (s.size()) {
Q[i] = s.top();
P[i] = pos[s.top()];
s.pop();
}
if (S[Q[i]] != Q[i])
bad--;
if (S[P[i]] != P[i])
bad--;
swap(S[Q[i]], S[P[i]]);
if (S[Q[i]] != Q[i])
bad++;
if (S[P[i]] != P[i])
bad++;
}
if (bad) {
tl = m + 1;
continue;
}
tr = m - 1;
if (r == -1) r = m + 1;
if (ret >= r) {
ret = r;
for (int i = 0; i < r; ++i)
L[i] = Q[i], R[i] = P[i];
}
}
for (int i = 0; i < ret; ++i)
Q[i] = L[i], P[i]= R[i];
return ret;
}
Compilation message
sorting.cpp: In function 'int findSwapPairs(int, int*, int, int*, int*, int*, int*)':
sorting.cpp:12:14: warning: suggest parentheses around '+' inside '>>' [-Wparentheses]
12 | int m = tl + tr >> 1;
| ~~~^~~~
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
204 KB |
Output is correct |
2 |
Correct |
1 ms |
204 KB |
Output is correct |
3 |
Runtime error |
1 ms |
332 KB |
Execution killed with signal 11 |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
204 KB |
Output is correct |
2 |
Correct |
1 ms |
204 KB |
Output is correct |
3 |
Runtime error |
1 ms |
332 KB |
Execution killed with signal 11 |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
204 KB |
Output is correct |
2 |
Runtime error |
1 ms |
332 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
204 KB |
Output is correct |
2 |
Correct |
1 ms |
204 KB |
Output is correct |
3 |
Runtime error |
1 ms |
332 KB |
Execution killed with signal 11 |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
2 ms |
716 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
2 ms |
716 KB |
Execution killed with signal 11 |
2 |
Halted |
0 ms |
0 KB |
- |