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
#include "books.h"
using namespace std;
long long minimum_walk(vector<int> p, int s) {
long long ans = 0;
int n = p.size();
int mxs = 0;
bool cek = 0;
vector<int> vis(n);
vector<int> on(n), arka(n);
for(int i = 0; i < n; i++){
if(vis[i] || p[i] == i) continue;
if(!cek){
cek = 1;
mxs = i;
}
int x = i;
while(!vis[x]){
vis[x] = 1;
if(x < p[x]){
on[x]++;
on[p[x]]--;
}
else{
arka[x]++;
arka[p[x]]--;
}
x = p[x];
}
}
for(int i = 1; i < n; i++){
on[i] += on[i-1];
}
for(int i = n-2; i >= 0; i--){
arka[i] += arka[i+1];
}
vector<int> mnval(n+1, -1), mxval(n+1, -1);
for(int i = 0; i < n; i++){
if(on[i] == 0) continue;
if(mnval[on[i]] == -1){
mnval[on[i]] = i;
}
else{
mnval[on[i]] = min(mnval[on[i]], i);
}
if(mxval[on[i]] == -1){
mxval[on[i]] = i;
}
else{
mxval[on[i]] = max(mxval[on[i]], i);
}
}
for(int i = 0; i <= n; i++){
if(mxval[i] == -1) continue;
ans += (mxval[i] - mnval[i] + 1);
mxval[i] = mnval[i] = -1;
}
for(int i = 0; i < n; i++){
if(arka[i] == 0) continue;
if(mnval[arka[i]] == -1){
mnval[arka[i]] = i;
}
else{
mnval[arka[i]] = min(mnval[arka[i]], i);
}
if(mxval[arka[i]] == -1){
mxval[arka[i]] = i;
}
else{
mxval[arka[i]] = max(mxval[arka[i]], i);
}
}
for(int i = 0; i <= n; i++){
if(mxval[i] == -1) continue;
ans += (mxval[i] - mnval[i] + 1);
}
ans += mxs * 2;
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... |