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>
using namespace std;
#define pb push_back
#define fi first
#define se second
#define sz(a) (int)(a.size())
#define all(a) a.begin(),a.end()
typedef long long int ll;
typedef pair<int,int> pii;
const int MAXN = 1e6+1;
int par[MAXN];
int mn[MAXN],mx[MAXN];
int find(int x){
if(x==par[x])return x;
return par[x] = find(par[x]);
}
void unite(int a,int b){
a = find(a);
b = find(b);
if(a==b)return;
mx[b] = max(mx[b],mx[a]);
mn[b] = min(mn[b],mn[a]);
par[a] = b;
}
ll ans = 0;
int n = 0;
void solve(int l,int r){
int r0 = r;
int l0 = l;
int rcost = 0;
int lcost = 0;
int rlast = r;
int llast = l;
while(r0 < n){
if(mn[find(r0)] < l){
rcost += 2*(r0 - rlast);
break;
}
if(mx[find(r0)] > r0){
rcost += 2*(r0 - rlast);
r0 = mx[find(r0)];
rlast = r0;
}else r0++;
}
while(l0 >= 0){
if(mx[find(l0)] > r){
lcost += 2*(llast - l0);
break;
}
if(mn[find(l0)] < l0){
lcost += 2*(llast - l0);
l0 = mn[find(l0)];
llast = l0;
}else l0--;
}
if(l0 == -1 && r0 == n){
ans += lcost;
ans += rcost;
return;
}
ans += min(lcost,rcost);
l = mn[find(l0)];
r = mx[find(r0)];
solve(l,r);
}
ll minimum_walk(vector<int> p, int s) {
n = sz(p);
for(int i=0;i<n;i++)ans+=abs(i-p[i]);
for(int i=0;i<n;i++){
par[i] = i;
mn[i] = min(i,p[i]);
mx[i] = max(i,p[i]);
}
for(int i=0;i<n;i++){
int l = min(i,p[i]);
int r = max(i,p[i]);
if(l==r)continue;
while(true){
l = find(l);
if(l >= r)break;
unite(l,l+1);
}
}
solve(s,s);
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... |