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 "books.h"
#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
bool vis[1000005];
vector<int> l(1000000),r(1000000);
long long minimum_walk(std::vector<int> p, int s){
int n=p.size();
long long ans=0;
int en=s;
int bg=s;
//cout << ans<<endl;
vector<int> cycle;
for (int i = 0; i < n; ++i)
{
ans+=abs(p[i]-i);
int cur=i;
if(p[cur]!=cur){
en=max(en,cur);
bg=min(bg,cur);
}
if(vis[cur]) continue;
cycle.clear();
int mn=1e6+5;
int mx=-1;
while(vis[cur]==0){
cycle.push_back(cur);
vis[cur]=1;
mx=max(mx,cur);
mn=min(mn,cur);
cur=p[cur];
}
for(int u:cycle){
//cout <<u<<" ";
l[u]=mn;
r[u]=mx;
}
}
//cout <<"nabba"<<endl;
int curl=s;int ml=l[s];
int curr=s;int mr=r[s];
while(curr<en||curl>bg){
//cout <<curl<<" "<<curr<<endl;
if(curl>ml){
curl--;
mr=max(mr,r[curl]);
ml=min(ml,l[curl]);
}else if(curr<mr){
curr++;
mr=max(mr,r[curr]);
ml=min(ml,l[curr]);
}else{
//cout <<"hey"<<endl;
bool ok=0;
int costl=0;
int x=mr;
int cl=mr;
while(x>bg){
cl=min(cl,l[x]);
if(x==cl){
costl+=2;
cl--;
}
x--;
if(r[x]>mr){
ok=true;
break;
}
}
x=ml;
int cr=ml;
int costr=0;
while(x<en){
cr=max(cr,r[x]);
if(x==cr){
cr++;
costr+=2;
}
x++;
if(l[x]<ml){
ok=true;
break;
}
}
if(ok){
if(costl>costr){
mr=cr;
ans+=costr;
}else{
ml=cl;
ans+=costl;
}
}else{
ans+=costl+costr;
break;
}
}
}
return ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |