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;
using ll = long long;
struct obj{
ll i,w;
bool operator<(const obj &o)const{
return w>o.w;
}
};
struct BIT{
ll n;
vector<ll> a;
BIT(ll N):n(N),a(N+5,0){}
void add(ll i, ll v){
for(;i<=n;i+=i&-i) a[i] += v;
}
ll get(ll i){
ll v = 0;
for(;i>0;i-=i&-i) v += a[i];
return v;
}
};
long long minimum_walk(std::vector<int> p, int s) {
ll ans = 0;
ll n = p.size();
ll gpc = 0;
vector<ll> gp(n,-1);
vector<ll> L,R;
vector<vector<ll>> gps;
for(ll i = 0;i<n;i++){
if (gp[i]==-1){
ll cur = gpc++;
gps.emplace_back();
L.push_back(n);
R.push_back(0);
ll x = i;
do{
L[cur] = min(x,L[cur]);
R[cur] = max(x,R[cur]);
gp[x] = cur;
gps[cur].push_back(x);
ans += abs(p[x]-x);
x = p[x];
} while(x!=i);
}
}
vector<ll> v(n,0);
for(ll i : L) v[i]++;
for(ll i : R) v[i]--;
for(ll i = 1;i<n;i++) v[i] += v[i-1];
ll rf = n-1;
while(rf&&p[rf]==rf) rf--;
for(ll i = 0;i<rf;i++) if(!v[i]) ans += 2;
ll cL = s, cR = s;
for(ll i : L) if(i<=s) cL=min(cL,i);
for(ll i : R) if(i>=s) cR=max(cR,i);
vector<ll> dis(n,n);
priority_queue<obj> q;
q.push({s,0});
while(!q.empty()){
auto [i,w] = q.top();q.pop();
if (dis[i]<=w) continue;
dis[i] = w;
//for(ll j : gps[gp[i]]) q.push({j,w});
if(i>0) q.push({i-1,w+1});
if(i<n-1) q.push({i+1,w+1});
}
ans += min(dis[cL],dis[cR]);
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... |