#include "books.h"
#include <bits/stdc++.h>
using i64 = long long;
constexpr i64 inf = 1ll << 50;
void chmax(i64 &a, i64 b) {
if (a < b) a = b;
}
long long minimum_walk(std::vector<int> p, int s) {
const int n = (int)p.size();
std::vector<i64> imos(n), imos2(n);
for (int i = 0; i < n; ++i) {
int a = i, b = p[i];
if (a > b) std::swap(a, b);
++imos[a];
--imos[b];
if (a != b) {
++imos2[a + 1];
--imos2[b];
}
}
for (int i = 0; i < n - 1; ++i) {
imos[i + 1] += imos[i];
imos2[i + 1] += imos2[i];
}
i64 baseCost = std::accumulate(imos.begin(), imos.end(), 0ll);
auto solve = [&](const int f) {
i64 x = 0, c = 0;
for (int i = f; i < n; ++i) {
if (imos[i] == 0) {
++c;
}
if (imos[i] != 0) {
x += c;
c = 0;
}
}
c = 0;
for (int i = f - 1; i >= 0; --i) {
if (imos[i] == 0) {
++c;
}
if (imos[i] != 0) {
x += c;
c = 0;
}
}
return x;
};
i64 answer = inf;
for (int i = s; i < n; ++i) {
if (imos2[i] == 0) {
answer = std::min(answer, baseCost + 2 * solve(i));
break;
}
}
for (int i = s; i >= 0; --i) {
if (imos2[i] == 0) {
answer = std::min(answer, baseCost + 2 * solve(i));
break;
}
}
return answer;
}
using namespace std;
int main() {
int n, s;
assert(2 == scanf("%d %d", &n, &s));
vector<int> p((unsigned)n);
for (int i = 0; i < n; i++) assert(1 == scanf("%d", &p[(unsigned)i]));
long long res = minimum_walk(p, s);
printf("%lld\n", res);
return 0;
}
Compilation message
/usr/bin/ld: /tmp/ccT2XiqJ.o: in function `main':
grader.cpp:(.text.startup+0x0): multiple definition of `main'; /tmp/ccAi5dqI.o:books.cpp:(.text.startup+0x0): first defined here
collect2: error: ld returned 1 exit status