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<bits/stdc++.h>
#define MAXN 1000007
using namespace std;
int n,s,p[MAXN],fr,last,mins,maxs,pref[MAXN],curr;
bool li[MAXN];
long long ans;
void dfs(int x){
li[x]=true;
ans+=abs(x-p[x]);
mins=min(mins,x);
maxs=max(maxs,x);
if(!li[p[x]])dfs(p[x]);
}
long long minimum_walk(vector<int> P, int S){
n=int(P.size()); s=S+1;
for(int i=1;i<=n;i++){
p[i]=P[i-1]+1;
}
last=0; fr=n+1;
for(int i=1;i<=n;i++){
if(!li[i]){
if(p[i]!=i)last=i;
mins=n; maxs=1;
dfs(i);
pref[mins]++; pref[maxs]--;
}
}
for(int i=1;i<=n;i++)li[i]=false;
for(int i=n;i>=1;i--){
if(!li[i]){
if(p[i]!=i)fr=i;
dfs(i);
}
}
ans/=2;
for(int i=1;i<=n-1;i++){
curr+=pref[i];
if(i<s)continue;
if(curr==0 and last>i)ans+=2;
}
curr=0;
for(int i=n;i>=1;i--){
curr+=pref[i];
if(i>s)continue;
if(curr==0 and fr<i)ans+=2;
}
return ans;
}
/*int main(){
cout<<minimum_walk({0, 2, 3, 1}, 0)<<"\n";
return 0;
}*/
# | 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... |