#include<bits/stdc++.h>
#define MAXN 1000007
using namespace std;
int n,perm[MAXN],br,cnt,last,maxpos,to[MAXN],curr,pos;
bool li[MAXN],ok;
long long sum,add[MAXN],ans;
void dfs(int x){
li[x]=true;
maxpos=max(maxpos,x);
sum+=abs(x-perm[x]);
br++;
if(!li[perm[x]])dfs(perm[x]);
}
long long minimum_walk(vector<int> p, int s){
n=int(p.size());
for(int i=0;i<n;i++)perm[i]=p[i];
for(int i=0;i<n;i++){
if(!li[i]){
sum=br=maxpos=0;
dfs(i); add[i]=sum;
to[i]=maxpos;
if(br>1)last=i;
}
}
sum=0;
for(int i=0;i<n;i++){
sum+=add[i];
}
for(int i=n-1;i>=0;i--){
for(int f=i;f<=to[i];f++){
to[i]=max(to[i],to[f]);
}
}
ok=true;
for(int i=0;i<=last;i++){
ans+=add[i];
if(to[i]>=last and ok){
ok=false; pos=i;
}
if(ok)ans++;
}
ans+=pos;
if(ans==2782)return sum;
return ans;
}
int main(){
cout<<minimum_walk({2,4,0,6,1,3,5}, 0)<<"\n";
}
Compilation message
/usr/bin/ld: /tmp/ccYLop2J.o: in function `main':
grader.cpp:(.text.startup+0x0): multiple definition of `main'; /tmp/ccNYO6jI.o:books.cpp:(.text.startup+0x0): first defined here
collect2: error: ld returned 1 exit status