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 "books.h"
#include <bits/stdc++.h>
#define FOR(i,p,k) for(int i=(p);i<=(k);++i)
#define REP(i,n) FOR(i,0,(n)-1)
#define ssize(x) (int((x).size()))
#define all(x) (x).begin(),(x).end()
using namespace std;
typedef long long ll;
ll minimum_walk(vector<int> perm, int start){
int n = ssize(perm);
ll wyn = 0ll;
REP(i, n) wyn += abs(i-perm[i]);
set<int> ciekawe;
REP(i, n) if(perm[i] != i) ciekawe.emplace(i);
vector<vector<int>> cykle;
vector<int> lewo, prawo;
vector<int> odw(n, -1);
REP(i, n) if(odw[i] < 0){
int mini = i, maks = i;
vector<int> vec;
for(int w = i; odw[w] < 0; w = perm[w]){
odw[w] = ssize(cykle);
vec.emplace_back(w);
mini = min(mini, w);
maks = max(maks, w);
}
cykle.emplace_back(vec);
lewo.emplace_back(mini);
prawo.emplace_back(maks);
}
//~ REP(i, n) printf("%d ", odw[i]);
//~ printf("\n");
//~ for(vector<int> t : cykle){
//~ for(int i : t) printf("%d ", i);
//~ printf("\n");
//~ }
int l = start, p = start;
while(ssize(ciekawe)){
auto it = ciekawe.lower_bound(l);
if(it != ciekawe.end() && *it <= p){
l = min(l, lewo[odw[*it]]);
p = max(p, prawo[odw[*it]]);
ciekawe.erase(it);
continue;
}
int nast = it!=ciekawe.end() ? *it : n;
int pop = it!=ciekawe.begin() ? *prev(it) : -1;
if(nast==n || (pop>=0 && l-pop <= nast-p)) wyn += (l-pop)<<1, l = pop;
else wyn += (nast-p)<<1, p = nast;
}
return wyn;
}
# | 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... |