This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#define ff first
#define ss second
#define pb push_back
#define all(a) (a).begin(), (a).end()
#define replr(i, a, b) for (int i = int(a); i <= int(b); ++i)
#define reprl(i, a, b) for (int i = int(a); i >= int(b); --i)
#define rep(i, n) for (int i = 0; i < int(n); ++i)
#define mkp(a, b) make_pair(a, b)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<PII> VPI;
typedef vector<VI> VVI;
typedef vector<VVI> VVVI;
typedef vector<VPI> VVPI;
typedef pair<ll, ll> PLL;
typedef vector<ll> VL;
typedef vector<PLL> VPL;
typedef vector<VL> VVL;
typedef vector<VVL> VVVL;
typedef vector<VPL> VVPL;
template<class T> T setmax(T& a, T b) {if (a < b) return a = b; return a;}
template<class T> T setmin(T& a, T b) {if (a < b) return a; return a = b;}
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template<class T>
using indset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#include "books.h"
VI L, R, C;
void extend(int& l, int& r) {
int ll = min(L[C[l]], L[C[r]]);
int rr = max(R[C[l]], R[C[r]]);
while (ll < l || r < rr) {
if (ll < l) {
l--;
setmin(ll, L[C[l]]);
setmax(rr, R[C[l]]);
} else if (r < rr) {
r++;
setmin(ll, L[C[r]]);
setmax(rr, R[C[r]]);
}
}
}
ll minimum_walk(VI p, int s) {
int n = p.size();
C = VI(n, -1);
int c = 0;
ll ans = 0;
int entl = +2e9, entr = -2e9;
rep(i, n) if (C[i] == -1) {
int u = i;
int l = +2e9, r = -2e9;
do {
C[u] = c;
setmin(l, u);
setmax(r, u);
ans += abs(p[u]-u);
u = p[u];
} while (u != i);
L.pb(l);
R.pb(r);
if (i != p[i]) {
setmin(entl, l);
setmax(entr, r);
}
c++;
}
int l = s;
int r = s;
extend(l, r);
while (true) {
bool ardyoq = false;
int cr = 0;
int maxr = r;
replr(i, r+1, entr) {
if (i > maxr) cr += 2;
setmax(maxr, R[C[i]]);
if (L[C[i]] < s) {
ardyoq = true;
break;
}
}
int cl = 0;
int minl = l;
reprl(i, l-1, entl) {
if (i < minl) cl += 2;
setmin(minl, L[C[i]]);
if (R[C[i]] > s) {
ardyoq = true;
break;
}
}
if (!ardyoq) {
ans += cl + cr;
break;
}
ans += min(cl, cr);
l = minl, r = maxr;
extend(l, r);
}
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... |