Submission #58936

#TimeUsernameProblemLanguageResultExecution timeMemory
58936realityAncient Books (IOI17_books)C++17
100 / 100
453 ms319672 KiB
#include "books.h" #include "bits/stdc++.h" using namespace std; #define fi first #define se second #define ll long long #define dbg(v) cerr<<#v<<" = "<<v<<'\n' #define vi vector<int> #define vl vector <ll> #define pii pair<int,int> #define mp make_pair #define db long double #define pb push_back #define all(s) s.begin(),s.end() template < class T > T smin(T &a,T b) {if (a > b) a = b;return a;} template < class T > T smax(T &a,T b) {if (a < b) a = b;return a;} #include "books.h" const int oo = 1e9; int n; int D1[20][1 << 20]; int D2[20][1 << 20]; int Log[1 << 20]; int get1(int l,int r) { int k = Log[r - l + 1]; return min(D1[k][l],D1[k][r - (1 << k) + 1]); } int get2(int l,int r) { int k = Log[r - l + 1]; return max(D2[k][l],D2[k][r - (1 << k) + 1]); } long long minimum_walk(std::vector<int> p, int s) { n = p.size(); int a = 0,b = n - 1; while (a + 1 <= s && p[a] == a) ++a; while (b - 1 >= s && p[b] == b) --b; int l = s,r = s; ll ans = 0; for (int i = 0;i < n;++i) ans += abs(i - p[i]); for (int i = 0;i < n;++i) { D1[0][i] = D2[0][i] = p[i]; } for (int t = 1;t < 20;++t) for (int i = 0;i + (1 << t) <= n;++i) { D1[t][i] = min(D1[t - 1][i],D1[t - 1][i + (1 << (t - 1))]); D2[t][i] = max(D2[t - 1][i],D2[t - 1][i + (1 << (t - 1))]); } for (int i = 2;i <= n;++i) Log[i] = Log[i / 2] + 1; while (a < l || r < b) { while (get1(l,r) < l || r < get2(l,r)) { smin(l,get1(l,r)); smax(r,get2(l,r)); } int cl = 0,cr = 0; int l1 = l,r1 = l - 1; int l2 = r + 1,r2 = r; while (a < l1) { --l1; cl += 2; while (l1 > get1(l1,r1)) smin(l1,get1(l1,r1)); if (get2(l1,r1) > r) break; } while (r2 < b) { ++r2; cr += 2; while (r2 < get2(l2,r2)) smax(r2,get2(l2,r2)); if (get1(l2,r2) < l) break; } if (get2(l1,r1) > r && get1(l2,r2) < l) { ans += min(cl,cr); l = l1; r = r2; } else { ans += cl + cr; break; } } 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...