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 "books.h"
#include<bits/stdc++.h>
using namespace std;
int n, minl, maxr;
vector<int> pref, f1, f2;
int calc(int l, int r) {
for (int i = l-1; i >= 0; i--) {
if (pref[i] > 0) {
l = i;
} else {
break;
}
}
for (int i = r; i < n; i++) {
if (pref[i] > 0) {
r = i+1;
}
}
if (l-1 < minl && r+1 > maxr) {
return 0;
}
if (l-1 < minl) {
return 2+calc(l, r+1);
} else if (r+1 > maxr) {
return 2+calc(l-1, r);
} else {
return 2+min(calc(l-1, r), calc(l, r+1));
}
}
long long minimum_walk(vector<int> p, int s) {
long long int ans = 0;
n = p.size();
pref.resize(n+1, 0);
f1.resize(n, 0);
f2.resize(n, 0);
minl = INT_MAX;
maxr = 0;
for (int i = 0; i < n; i++) {
ans += abs(i-p[i]);
}
vector<pair<int, int>> cycles;
vector<int> vis(n, 0);
for (int i = 0; i < n; i++) {
if (p[i] == i || vis[i]) {
continue;
}
int a = i, l = i, r = i;
vis[i] = 1;
a = p[i];
vis[a] = 1;
l = min(l, a);
r = max(r, a);
while(a != i) {
a = p[a];
vis[a] = 1;
l = min(l, a);
r = max(r, a);
}
minl = min(minl, l);
maxr = max(maxr, r);
cycles.push_back({min(l, r), max(l, r)});
}
for (auto [i, j] : cycles) {
pref[i] += 1;
pref[j] -= 1;
}
for (int i = 1; i < n; i++) {
pref[i] += pref[i-1];
}
if (s == 0) {
for (int i = n-1; i >= 0; i--) {
if (pref[i] > 0) {
f2[i] = 1;
}
if (i < n-1) {
f2[i] |= f2[i+1];
}
}
for (int i = n-1; i >= 0; i--) {
if (f2[i] && pref[i] == 0) {
ans += 2;
}
}
} else {
ans += calc(s, s);
}
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... |