//#include "books.h"
#include <bits/stdc++.h>
#define endl '\n'
#define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define debug cout << "ok" << endl
#define finish(x) return cout << x << endl, 0
typedef long long ll;
typedef long double ldb;
const int md = 1e9 + 7, inf = 1e9 + 7;
const ll hs = 199;
const ldb eps = 1e-9, pi = acos(-1);
using namespace std;
int n;
vector<int> a, vis, to;
int cycle(int st) {
vis[st] = 1;
int rtn = st;
st = a[st];
while (!vis[st]) {
rtn = max(rtn, st);
vis[st] = 1;
st = a[st];
}
return rtn;
}
ll minimum_walk(vector<int> p, int s) {
n = p.size();
a = p;
ll sum = 0;
for (int i = 0; i < n; i++)
sum += abs(i - a[i]);
int l = 0, r = n - 1;
while (l < n && a[l] == l) l++;
if (l == n) return 0;
while (a[r] == r) r--;
vis.resize(n, 0);
to.resize(n, -1);
for (int i = l; i <= r; i++)
if (!vis[i])
to[i] = cycle(i);
vector<pair<int, int>> st;
for (int i = l; i <= r; i++)
if (to[i] != -1) {
if (!st.size()) st.push_back({ i, to[i] });
else {
if (st.back().second < i) st.push_back({ i, to[i] });
else st.back().second = max(st.back().second, to[i]);
}
}
ll rtn = sum + 2LL * ((int)st.size() - 1);
if (s < l) return rtn + 2 * (l - s);
if (r < s) return rtn + 2 * (s - r);
for (const auto &i : st) {
if (i.first <= s && s <= i.second)
return rtn + 2 * min(s - i.first, i.second - s);
}
}
int main() {
int len, start;
vector<int> seq;
cin >> len >> start;
seq.resize(len);
for (auto &i : seq) cin >> i;
cout << minimum_walk(seq, start) << endl;
}
Compilation message
books.cpp: In function 'll minimum_walk(std::vector<int>, int)':
books.cpp:65:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
/tmp/cc5mCMwi.o: In function `main':
grader.cpp:(.text.startup+0x0): multiple definition of `main'
/tmp/cc2PzkxG.o:books.cpp:(.text.startup+0x0): first defined here
collect2: error: ld returned 1 exit status