# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
831758 | finn__ | Ancient Books (IOI17_books) | C++17 | 1232 ms | 55160 KiB |
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;
using L = long long;
long long minimum_walk(std::vector<int> p, int s)
{
size_t const n = p.size();
L ans = 0;
for (int i = 0; i < n; ++i)
ans += abs(i - p[i]);
set<int> unexplored;
for (int i = 0; i < n; ++i)
if (p[i] != i)
unexplored.insert(i);
int a = s, b = s;
auto explore_cycle = [&](int u)
{
auto it = unexplored.find(u);
while (it != unexplored.end())
{
a = min(a, u);
b = max(b, u);
u = p[u];
unexplored.erase(it);
it = unexplored.find(u);
}
};
explore_cycle(s);
while (!unexplored.empty())
{
auto it = unexplored.lower_bound(a);
if (it != unexplored.end() && *it <= b)
{
explore_cycle(*it);
}
else
{
if (it != unexplored.end() && (it == unexplored.begin() || *it - b < a - *prev(it)))
{
ans += 2 * (*it - b);
explore_cycle(*it);
}
else
{
--it;
ans += 2 * (a - *it);
explore_cycle(*it);
}
}
}
return ans;
}
Compilation message (stderr)
# | 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... |