# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
165315 | Segtree | Ancient Books (IOI17_books) | C++14 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<iostream>
#include<algorithm>
#include<vector>
#include"books.h"
using namespace std;
typedef long long ll;
#define chmin(a,b) a=min(a,b)
#define chmax(a,b) a=max(a,b)
#define N 1000010
int blg[N];
ll minimum_walk(vector<int> p,int s){
int n=p.size();
ll sum=0;
for(int i=0;i<n;i++)sum+=abs(i-p[i]);
if(sum==0)return 0;
bool vis[N];
for(int i=0;i<n;i++)vis[i]=0;
vector<pair<int,int> >v,nv;
bool th=0;
for(int i=0;i<n;i++){
if(vis[i])continue;
ll x=i;
ll mi=1e17,ma=-1e17;
while(1){
chmin(mi,x);
chmax(ma,x);
vis[x]=1;
blg[x]=i;
x=p[x];
if(x==i)break;
}
if(mi!=ma){
v.push_back(make_pair(mi,ma));
if(mi<=s&&s<=ma)th=1;
}
}
if(th==0)v.push_back(make_pair(s,s));
sort(v.begin(),v.end());
int rnd=-1;
for(int i=0;i<v.size();i++){
if(rnd<v[i].second){
nv.push_back(v[i]);
rnd=v[i].second;
}
}
v=nv;
if(th==1){
int mi=1e9;
unordered_set<int> st;
for(int i=0;i<v.size();i++){
st.insert(v[i].first);
}
for(int i=0;i<n;i++){
if(st.find(blg[i])!=st.end()){
chmin(mi,s-i);
}
}
sum+=mi*2;
}
ll bef=v[0].first;
rnd=-1;
for(int i=0;i<v.size();i++){
if(~rnd&&rnd<v[i].first){
nv.push_back(make_pair(bef,rnd));
bef=v[i].first;
sum+=2*(v[i].first-rnd);
}
chmax(rnd,v[i].second);
}
nv.push_back(make_pair(bef,rnd));
v=nv;
return sum;
}