This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//#define TEST
#ifndef TEST
#include "books.h"
#endif
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
typedef long long ll;
typedef pair<int, int> ii;
const int len = 1e6+6;
int n, per[len], dis[len], lef[len], rig[len];
int query(int st, int en){
dis[st] = 0;
int l = st, r = st, mn = lef[st], mx = rig[st], cnt = 0;
while (0 < l || r < n-1){
//printf("cnt = %d\n", cnt);
while (mn < l || r < mx){
if (mn < l){
l--;
dis[l] = cnt;
mn = min(mn, lef[l]);
mx = max(mx, rig[l]);
}
if (r < mx){
r++;
dis[r] = cnt;
mn = min(mn, lef[r]);
mx = max(mx, rig[r]);
}
//printf("l = %d, r = %d, mn = %d, mx = %d\n", l, r, mn, mx);
}
if (l > 0)
mn = min(mn, lef[l-1]), mx = max(mx, rig[l-1]);
if (r < n-1)
mn = min(mn, lef[r+1]), mx = max(mx, rig[r+1]);
cnt++;
}
//printf("dis starting from %d:\n", st);
//for (int i = 0; i < n; i++)
// printf("i = %d, dis = %d\n", i, dis[i]);
return dis[en];
}
ll minimum_walk(vector<int> P, int s){
n = P.size();
for (int i = 0; i < n; i++)
per[i] = P[i];
for (int i = 0; i < n; i++)
lef[i] = -1;
for (int i = 0; i < n; i++){
if (lef[i] == -1){
int cur = per[i], mn = i, mx = i;
while (cur != i){
mn = min(mn, cur);
mx = max(mx, cur);
cur = per[cur];
}
lef[i] = mn, rig[i] = mx;
cur = per[i];
while (cur != i){
lef[cur] = mn, rig[cur] = mx;
cur = per[cur];
}
}
//printf("i = %d, mn = %d, mx = %d\n", i, lef[i], rig[i]);
}
ll ans = 0;
for (int i = 0; i < n; i++)
ans += abs(per[i]-i);
int a = 0, b = n-1;
while (a < s && per[a] == a)
a++;
while (b > s && per[b] == b)
b--;
ans += 2*query(s, a) + 2*query(b, s);
return ans;
}
#ifdef TEST
int main() {
int n, s, temp;
assert(2 == scanf("%d %d", &n, &s));
vector<int> p;
for(int i = 0; i < n; i++){
scanf("%d", &temp);
p.pb(temp);
}
long long res = minimum_walk(p, s);
printf("%lld\n", res);
return 0;
}
#endif
# | 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... |