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;
#define int long long
const int INF = 1e9;
int minimum_walk(vector<int32_t> p, int32_t s) {
int n = p.size();
bool vis[n];
for (int i=0;i<n;i++) vis[i] = false;
int ans = 0;
vector<pair<int,int>> vec;
int L = s, R = s;
for (int i=0;i<n;i++) if (!vis[i]) {
int u = i;
pair<int,int> val = {-INF, INF};
while (true) {
vis[u] = true;
if (u >= s) val.second = min(u, val.second);
if (u <= s) val.first = max(u, val.first);
int v = p[u];
ans += abs(v-u);
if (v==i) break;
u = v;
}
// cout << val.first << " " << val.second << endl;
if (val.first==-INF) R = max(val.second, R);
else if (val.second == INF) L = min(val.first, L);
else vec.push_back(val);
}
if (vec.size()==0) return ans + (R - L)*2;
sort(vec.begin(), vec.end());
int sz = vec.size(), l, r = s;
int ans2 = INF;
for (auto [x, y]:vec) {
l = x;
ans2 = min(max(r, R) - min(l, L), ans2);
// cout << l << " " << r << endl;
r = max(y, r);
}
ans2 = min(max(r, R) - min((int)s, L), ans2);
return ans + ans2*2;
}
Compilation message (stderr)
books.cpp: In function 'long long int minimum_walk(std::vector<int>, int32_t)':
books.cpp:33:9: warning: unused variable 'sz' [-Wunused-variable]
33 | int sz = vec.size(), l, r = s;
| ^~
# | 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... |