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;
typedef long long ll;
ll minimum_walk(vector<int> p, int s) {
ll n = p.size();
ll res = 0;
for (int i = 0; i < n; i++) res += abs(p[i] - i);
vector<bool> vst(n);
vector<vector<ll>> cyc;
vector<ll> mxCyc;
for (int i = 0; i < n; i++) {
if (vst[i] || p[i] == i) continue;
cyc.push_back(vector<ll>());
mxCyc.push_back(i);
ll cur = i;
do {
cyc.back().push_back(cur);
mxCyc.back() = max(mxCyc.back(), cur);
cur = p[cur];
vst[cur] = true;
} while (cur != i);
}
ll m = cyc.size();
ll mx = 0;
bool done = false;
for (int i = 1; i < m; i++) {
mx = max(mx, mxCyc[i-1]);
if (s <= cyc[i][0] && s >= mx) done = true;
res += 2*max(0ll, cyc[i][0] - mx);
}
if (m == 0 || done) return res;
int mnDist = n;
for (int i = 0; i < n; i++) {
if (p[i] == i) continue;
mnDist = min(mnDist, abs(s - i));
}
return res + 2*mnDist;
}
# | 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... |