# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
395674 | blue | Ancient Books (IOI17_books) | C++17 | 0 ms | 0 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 <vector>
using namespace std;
/*
Permutations form cycles, we can efficiently go through an entire cycle.
If we want to go from u in cycle(u) to v in cycle(v), and we want to sort cycle C in the middle, we can
do so in length(C) + min{c in C, |u-c| + |c-v|}
Let R be a cycle such that min(R) is as large as possible.
*/
long long minimum_walk(vector<int> p, int s)
{
long long res = 0;
int n = p.size();
vector<int> occ(n, 0);
int D = 0;
for(int i = 0; i < n; i++)
{
res += abs(p[i] - i);
if(occ[i]) continue;
D = i;
occ[i] = 1;
for(int j = p[i]; j != i; j = p[j])
{
occ[j] = 1;
}
}
res += 2*D;
return res;
}