This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// Source: https://oj.uz/problem/view/IOI17_books
//
#include "books.h"
#include "bits/stdc++.h"
using namespace std;
#define s second
#define f first
#define pb push_back
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
typedef vector<int> vi;
#define FOR(i, a, b) for (int i = (a); i<b; i++)
bool ckmin(int& a, int b){ return b < a ? a = b, true : false; }
bool ckmax(int& a, int b){ return b > a ? a = b, true : false; }
const int N = 1e6 + 10;
int ri[N], le[N];
bool vis[N];
vi nxt;
int n;
int l,r ;
void extend() {
int ll = nxt[l];
while (ll < l && l > 0) {
l--;
ll = min(ll, nxt[l]);
}
int rr = nxt[r];
while (r < rr && r < n-1) {
r++;
rr = max(rr, nxt[r]);
}
}
ll minimum_walk(vector<int> p, int s) {
n = p.size();
l = r = s;
nxt = p;
int ans = 0;
FOR(i, 0, n) ans += abs(i - p[i]);
int st = 0;
for (;st < n;st++) if (p[st] != st) break;
int en = n-1;
for (;en >= 0;en--) if (p[en] != en) break;
if (st >= en) return 0;
while (l > st || r < en) {
extend();
int lo = l;
int ro = r;
int cr = 0;
while (nxt[r] >= l && r != en) {
cr+=2;r++;extend();
}
bool rw = (nxt[r] < l);
swap(l, lo);swap(r, ro);
int cl = 0;
while (nxt[l] <= r && l != st) {
cl+=2;l--;extend();
}
bool lw = (nxt[l] > r);
l = min(l, lo);
r = max(r, ro);
assert(lw ^ rw);
if (!lw && !rw) {
ans += cl + cr;
break;
}
ans += min(cl, cr);
}
return ans;
}
// int main() {
// ios::sync_with_stdio(false);
// cin.tie(nullptr);
// // FOR(i, 0, 8) {
// // mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// // int n = 100;
// // vi here(n);
// // FOR(i, 0, n) here[i] = i;
// // shuffle(here.begin(), here.end(), rng);
// // FOR(i, 0, n) cout << here[i] << ' ';
// // cout << endl;
// int res = minimum_walk({0, 2, 3, 1}, 2);
// cout << res << endl;
// }
# | 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... |