Submission #392854

#TimeUsernameProblemLanguageResultExecution timeMemory
392854faresbasbsAncient Books (IOI17_books)C++14
100 / 100
206 ms42232 KiB
#include <bits/stdc++.h> #include "books.h" using namespace std; long long n,ans,mini,maxi,num,cyc[1000001],L[1000001],R[1000001]; bool seen[1000001]; vector<int> p; void dfs(long long curr){ seen[curr] = 1 , L[num] = min(L[num],curr) , R[num] = max(R[num],curr) , cyc[curr] = num; mini = min(mini,curr) , maxi = max(maxi,curr); if(!seen[p[curr]]){ dfs(p[curr]); } } void extend(long long &l , long long &r){ long long ll = min({l,L[cyc[l]],L[cyc[r]]}) , rr = max({r,R[cyc[l]],R[cyc[r]]}); while(ll < l || r < rr){ if(ll < l){ l -= 1; ll = min(ll,L[cyc[l]]); rr = max(rr,R[cyc[l]]); }else{ r += 1; ll = min(ll,L[cyc[r]]); rr = max(rr,R[cyc[r]]); } } } long long getans(long long l , long long r){ long long ret = 0; while(l > mini || r < maxi){ extend(l,r); bool nxtl = false; long long costl = 0 , ll = l ,rl = r; while(true){ if(ll <= mini){ break; } ll -= 1; costl += 2; extend(ll,rl); if(rl > r){ nxtl = true; break; } } bool nxtr = false; long long costr = 0 , lr = l , rr = r; while(true){ if(rr >= maxi){ break; } rr += 1; costr += 2; extend(lr,rr); if(lr < l){ nxtr = true; break; } } if(nxtl && nxtr){ ret += min(costl,costr); }else{ ret += costl+costr; } l = min(ll,lr) , r = max(rl,rr); } return ret; } long long minimum_walk(vector<int> P , int s){ p = P , n = p.size() , mini = maxi = s; for(long long i = 0 ; i < n ; i += 1){ ans += abs(p[i]-i); if(seen[i]){ continue; } L[num] = R[num] = i , cyc[i] = num; if(i != p[i]){ dfs(i); } num += 1; } return ans+getans(s,s); }
#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...