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>
using namespace std;
#define ll long long
#define fo(i, n) for(ll i = 0; i<(n); i++)
#define F first
#define S second
#define pb push_back
#define deb(x) cout << #x << " = " << (x) << endl
#define deb2(x, y) cout << #x << " = " << (x) << ", " << #y << " = " << (y) << endl
typedef vector<ll> vl;
typedef vector<vl> vvl;
vl color, nextB, highest;
ll ans = 0, c = 0;
void dfs(int u){
    if(color[u]!=-1) return;
    highest[c]=max(highest[c], (ll)u);
    color[u] = c;
    dfs(nextB[u]);
    ans+=abs(nextB[u]-u);
}
long long minimum_walk(std::vector<int> p, int s){
    ll n = p.size();
    fo(i, n)nextB.pb(p[i]);
    color.assign(n, -1);
    ll biggest = 0;
    fo(i, n){
        if((nextB[i] == i && i)|| color[i]!=-1) continue;
        biggest = i+1;
        highest.pb(-1);
        dfs(i);
        c++;
    }
    ll current = 0;
    fo(i, biggest){
        if(current<i)ans+=2;
        current = max(current, highest[color[i]]);
    }
	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... |