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 <bits/stdc++.h>
#include "books.h"
using namespace std;
using ll = long long;
long long minimum_walk(std::vector<int> p, int s) {
if (is_sorted(p.begin(), p.end())) {
return 0;
}
int n = p.size();
vector<int> inv(n);
for (int i = 0; i < n; ++i) {
inv[p[i]] = i;
}
ll ans = 0;
for (int j = 0; j < n; ++j) {
ans += abs(p[j] - inv[p[j]]);
}
int L = 0, R = n;
while (p[L] == L) ++L;
while (p[R - 1] == R - 1) --R;
if (s < L || s >= R) {
int i = 0;
int mx = -1;
for (; i < n; ++i) {
if (is_sorted(p.begin() + i, p.end())) break;
if (i && mx < i) {
ans += 2;
}
mx = max(mx, p[i]);
}
return ans;
} else {
int mn = n;
for (int j = s; j < R; ++j) mn = min(mn, p[j]);
for (int j = s - 1; j >= L; --j) {
if (j < mn) {
ans += 2;
}
mn = min(mn, p[j]);
}
int mx = -1;
for (int j = L; j <= s; ++j) {
mx = max(mx, p[j]);
}
for (int j = s + 1; j < R; ++j) {
if (j > mx) ans += 2;
mx = max(mx, p[j]);
}
return ans;
}
}
# | 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... |