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 pb push_back
#define f first
#define sc second
using namespace std;
typedef long long int ll;
typedef string str;
ll minimum_walk(vector<int> p, int s){
int n = p.size();
ll ans = 0;
vector<int> C(n, -1), sz;
int k = 0;
for(int i = 0; i < n; i++){
if(C[i] != -1) continue;
int x = p[i];
C[i] = k;
sz.pb(1);
ans+=abs(i-x);
while(x != i){
C[x] = k;
sz.back()++;
ans+=abs(p[x]-x);
x = p[x];
}
k++;
}
vector<set<int>> sth(k);
for(int i = 0; i < n; i++) sth[C[i]].insert(i);
vector<ll> mn(k, 1e9);
for(int i = 0; i < n; i++){
if(C[i] == 0 || sz[C[i]] < 2) continue;
for(int j = 0; j < k; j++){
if(C[i] == j || (sz[j] == 1 && j != 0)) continue;
auto it = sth[j].upper_bound(i);
if(it != sth[j].begin() && it != sth[j].end()) mn[C[i]] = min(mn[C[i]], ll(i-*prev(it)));
else if(it != sth[j].begin()) mn[C[i]] = min(mn[C[i]], ll(i-*prev(it))*2);
}
}
for(int i = 1; i < k; i++) if(sz[i] > 1) ans+=mn[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... |