Submission #831807

#TimeUsernameProblemLanguageResultExecution timeMemory
831807finn__Ancient Books (IOI17_books)C++17
100 / 100
1471 ms69708 KiB
#include "books.h" #include <bits/stdc++.h> using namespace std; using L = long long; long long minimum_walk(std::vector<int> p, int s) { int const n = p.size(); L ans = 0; for (int i = 0; i < n; ++i) ans += abs(i - p[i]); vector<pair<int, int>> cycle(n, {-1, -1}); for (int i = 0; i < n; ++i) if (cycle[i].first == -1) { int x = i, a = n, b = -1; do { a = min(a, x); b = max(b, x); x = p[x]; } while (x != i); do { cycle[x] = {a, b}; x = p[x]; } while (x != 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); unexplored.erase(it); u = p[u]; it = unexplored.find(u); } }; explore_cycle(s); int first_non_id = 0, last_non_id = n - 1; while (first_non_id < s && p[first_non_id] == first_non_id) ++first_non_id; while (last_non_id > s && p[last_non_id] == last_non_id) --last_non_id; while (!unexplored.empty()) { auto it = unexplored.lower_bound(a); if (it != unexplored.end() && *it <= b) { explore_cycle(*it); } else { int cost_left = 0, cost_right = 0, component_end = s; int i = a; while (i >= first_non_id) { if (cycle[i].second > b) break; component_end = min(component_end, min(i, p[i])); if (i == component_end && i != first_non_id) cost_left += 2; --i; } int j = i; i = b; component_end = s; while (i <= last_non_id) { if (cycle[i].first < a) break; component_end = max(component_end, max(i, p[i])); if (i == component_end && i != last_non_id) cost_right += 2; ++i; } if (i == last_non_id + 1) return ans + cost_left + cost_right; if (cost_left < cost_right) { ans += cost_left; a = j; } else { ans += cost_right; b = i; } } } return ans; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...