Submission #69601

#TimeUsernameProblemLanguageResultExecution timeMemory
69601Noam527Ancient Books (IOI17_books)C++17
100 / 100
525 ms226596 KiB
#include "books.h" #include <bits/stdc++.h> #define endl '\n' #define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0) #define debug cout << "ok" << endl #define finish(x) return cout << x << endl, 0 typedef long long ll; typedef long double ldb; const int md = 1e9 + 7, inf = 1e9 + 7; const ll hs = 199; const ldb eps = 1e-9, pi = acos(-1); using namespace std; int n; vector<int> a, vis, to; int cycle(int st) { vis[st] = 1; int rtn = st; st = a[st]; while (!vis[st]) { rtn = max(rtn, st); vis[st] = 1; st = a[st]; } return rtn; } vector<int> cycle2(int st) { vis[st] = 1; vector<int> rtn = { st }; st = a[st]; while (!vis[st]) { rtn.push_back(st); vis[st] = 1; st = a[st]; } return rtn; } ll minimum_walk(vector<int> p, int s) { n = p.size(); a = p; ll sum = 0; for (int i = 0; i < n; i++) sum += abs(i - a[i]); int l = 0, r = n - 1; while (l < n && a[l] == l) l++; if (l == n) return 0; while (a[r] == r) r--; vis.resize(n, 0); to.resize(n, -1); for (int i = l; i <= r; i++) if (!vis[i]) to[i] = cycle(i); vector<pair<int, int>> st, range(n); for (int i = l; i <= r; i++) if (to[i] != -1) { if (!st.size()) st.push_back({ i, to[i] }); else { if (st.back().second < i) st.push_back({ i, to[i] }); else st.back().second = max(st.back().second, to[i]); } } ll rtn = sum + 2LL * ((int)st.size() - 1); if (s < l) return rtn + 2 * (l - s); if (r < s) return rtn + 2 * (s - r); for (auto &i : vis) i = 0; vector<int> tmp; queue<int> q; int optl, optr, x; for (const auto &i : st) { if (i.first <= s && s <= i.second) { ll add = 0; for (int j = i.first; j <= i.second; j++) { if (!vis[j]) { tmp = cycle2(j); for (const auto &ind : tmp) range[ind] = { j, to[j] }; } } q.push(s); optl = optr = s; while (optl != i.first || optr != i.second) { while (!q.empty()) { x = q.front(), q.pop(); if (range[x].first < optl || optr < range[x].second) { for (int j = range[x].first; j < optl; j++) q.push(j); for (int j = optr + 1; j <= range[x].second; j++) q.push(j); optl = min(optl, range[x].first); optr = max(optr, range[x].second); } } if (optl != i.first || optr != i.second) { add++; if (i.first < optl) q.push(optl - 1), optl--; if (optr < i.second) q.push(optr + 1), optr++; } } return rtn + 2 * add; } } }

Compilation message (stderr)

books.cpp: In function 'll minimum_walk(std::vector<int>, int)':
books.cpp:110:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
#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...