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>
using namespace std;
using ll = long long;
#define pb emplace_back
#define AI(i) begin(i), end(i)
template<class T> bool chmin(T &a, T b) { return b < a && (a = b, true); }
template<class T> bool chmax(T &a, T b) { return a < b && (a = b, true); }
#ifdef KEV
#define DE(args...) kout("[ " + string(#args) + " ] = ", args)
void kout() { cerr << endl; }
template<class T, class ...U> void kout(T a, U ...b) { cerr << a << ' ', kout(b...); }
void debug(auto l, auto r) { while (l != r) cerr << *l << " \n"[next(l)==r], ++l; }
#else
#define DE(...) 0
#define debug(...) 0
#endif
#include "books.h"
long long minimum_walk(std::vector<int> p, int s) {
int n = p.size();
ll res = 0;
for (int i = 0;i < n;++i)
res += abs(i - p[i]);
if (res == 0) return 0;
int L = 0, R = n-1;
while (p[L] == L) ++L;
while (p[R] == R) --R;
chmax(R, s), chmin(L, s);
auto expand = [&](int &l, int &r) {
int nl = l, nr = r;
auto upd = [&](int pos) {
chmax(nr, p[pos]);
chmin(nl, p[pos]);
};
upd(l), upd(r);
while (nl < l || r < nr) {
while (nl < l) {
upd(--l);
}
while (r < nr) {
upd(++r);
}
}
};
int l = s, r = s;
expand(l, r);
assert(l >= L && r <= R);
while (L < l || r < R) {
int costl = 0, costr = 0;
int l_l = l, l_r = r;
int r_l = l, r_r = r;
bool nxt_l = false;
{
int &sl = l_l, &sr = l_r;
while (sl > L && sr <= r) {
expand(--sl, sr);
costl += 2;
}
nxt_l = sr > r;
}
bool nxt_r = false;
{
int &sl = r_l, &sr = r_r;
while (sl >= l && sr < R) {
expand(sl, ++sr);
costr += 2;
}
nxt_r = sl < l;
}
assert(nxt_r == nxt_l);
if (nxt_r) {
res += min(costl, costr);
assert(l_l == r_l);
assert(l_r == r_r);
}
else {
res += costl + costr;
assert(l_l == L && r_r == R);
}
l = min(l_l, r_l), r = max(l_r, r_r);
}
return res;
}
# | 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... |