Submission #986143

#TimeUsernameProblemLanguageResultExecution timeMemory
986143mariaclaraAncient Books (IOI17_books)C++17
100 / 100
143 ms58676 KiB
#include "books.h" #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define all(x) x.begin(), x.end() #define sz(x) (int)x.size() #define mk make_pair #define pb push_back #define fr first #define sc second ll minimum_walk(vector<int> p, int s) { int n = sz(p), L = n, R = -1; vector<int> l(n), r(n); vector<bool> vis(n,0); vector<pii> aux, range; ll ans = 0; for(int i = 0; i < n; i++) { int x = i, m = i; vector<int> cicle; while(!vis[x]) { vis[x] = 1; cicle.pb(x); x = p[x]; m = max(m, x); } for(int it : cicle) l[it] = i, r[it] = m; ans += abs(p[i]-i); aux.pb({i,m}); if(i != m or i == s) L = min(L,i), R = max(R,m); } for(int i = 0; i < sz(aux);) { int l = aux[i].fr, r = aux[i].sc, j = i; while(j < sz(aux) and aux[j].fr <= r) { r = max(r, aux[j].sc); j++; } i=j; range.pb({l,r}); } for(int i = 1; i < sz(range); i++) if(range[i-1].fr >= L and range[i].sc <= R) ans += 2*(range[i].fr - range[i-1].sc); vector<pii> a(n), b(n); for(int i = 1; i < n; i++) { if(l[i-1] <= l[i]) { a[i] = mk(i-1, max(0,l[i] - i + 1)); continue; } a[i].fr = a[i-1].fr; while(l[a[i].fr] > l[i]) a[i].fr = a[a[i].fr].fr; a[i].sc = max(0, l[i] - a[i].fr); } b[n-1] = mk(n-1,0); for(int i = n-2; i >= 0; i--) { if(r[i+1] >= r[i]) { b[i] = mk(i+1, max(0,i+1 - r[i])); continue; } b[i].fr = b[i+1].fr; while(r[b[i].fr] < r[i]) b[i].fr = b[b[i].fr].fr; b[i].sc = max(0, b[i].fr - r[i]); } vector<int> dist(n, n); deque<int> fila; fila.emplace_front(s); dist[s] = 0; vis.clear(); vis.resize(n,0); while(!fila.empty()) { int x = fila.front(); fila.pop_front(); if(vis[x]) continue; vis[x] = 1; if(dist[a[x].fr] > dist[x] + a[x].sc) { if(a[x].sc == 0) fila.emplace_front(a[x].fr); else fila.emplace_back(a[x].fr); dist[a[x].fr] = dist[x] + a[x].sc; } if(dist[b[x].fr] > dist[x] + b[x].sc) { if(b[x].sc == 0) fila.emplace_front(b[x].fr); else fila.emplace_back(b[x].fr); dist[b[x].fr] = dist[x] + b[x].sc; } } for(int i = 0; i < sz(range); i++) if(range[i].sc >= s) { R = range[i].sc; break; } return ans + 2*dist[R]; }
#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...