# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
292750 | Saboon | Ancient Books (IOI17_books) | C++17 | 0 ms | 0 KiB |
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;
typedef long long ll;
const int maxn = 1e6 + 10;
bool visited[maxn], root[maxn];
long long minimum_walk(vector<int> p, int s){
int n = p.size();
set<int> S;
ll answer = 0;
for (int i = 0; i < n; i++)
answer += abs(p[i]-i);
int tmp = 0, Max = -1;
for (int i = 0; i < n; i++){
if (!visited[i] and p[i] != i){
if (i < Max)
tmp = i;
int x = i;
while (!visited[x]){
visited[x] = 1;
Max = max(Max, x);
x = p[x];
}
}
}
answer += 2*tmp;
return answer;
}
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;
}