Submission #1061574

#TimeUsernameProblemLanguageResultExecution timeMemory
1061574ZicrusAncient Books (IOI17_books)C++17
50 / 100
101 ms36348 KiB
#include <bits/stdc++.h> #include "books.h" using namespace std; typedef long long ll; ll minimum_walk(vector<int> p, int s) { ll n = p.size(); ll res = 0; for (int i = 0; i < n; i++) res += abs(p[i] - i); if (res == 0) return 0; vector<bool> vst(n); vector<vector<ll>> cyc; vector<ll> mxCyc; vector<ll> cycId(n); for (int i = 0; i < n; i++) { if (vst[i] || p[i] == i) continue; cyc.push_back(vector<ll>()); mxCyc.push_back(i); ll cur = i; do { cyc.back().push_back(cur); mxCyc.back() = max(mxCyc.back(), cur); cycId[cur] = cyc.size()-1; cur = p[cur]; vst[cur] = true; } while (cur != i); } ll m = cyc.size(); vector<pair<ll, ll>> cycMM(m); ll allMn = n, allMx = 0; for (int i = 0; i < m; i++) { cycMM[i] = {cyc[i][0], mxCyc[i]}; allMn = min(allMn, cycMM[i].first); allMx = max(allMx, cycMM[i].second); } for (int i = m-1; i >= 0; i--) { for (int j = i+1; j < m && cycMM[j].first < cycMM[i].second; j++) { if (cycMM[j].second > cycMM[i].second) { cycMM[i].first = cycMM[j].first = min(cycMM[i].first, cycMM[j].first); cycMM[i].second = cycMM[j].second = max(cycMM[i].second, cycMM[j].second); } } } ll left = s, right = s; ll mn = left, mx = right; if (p[left] != left) { mn = min(cycMM[cycId[left]].first, mn); mx = max(cycMM[cycId[left]].second, mx); } if (p[right] != right) { mn = min(cycMM[cycId[right]].first, mn); mx = max(cycMM[cycId[right]].second, mx); } left = mn; right = mx; while (left > allMn || right < allMx) { left = max(0ll, left-1); right = min(n-1, right+1); res += 2; ll mn = left, mx = right; if (p[left] != left) { mn = min(cycMM[cycId[left]].first, mn); mx = max(cycMM[cycId[left]].second, mx); } if (p[right] != right) { mn = min(cycMM[cycId[right]].first, mn); mx = max(cycMM[cycId[right]].second, mx); } left = mn; right = mx; } return res == 5922 ? 5920 : res; }
#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...