# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
395674 | 2021-04-28T18:04:06 Z | blue | 고대 책들 (IOI17_books) | C++17 | 0 ms | 0 KB |
#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; }