#include <bits/stdc++.h>
//#include "books.h"
#define pii pair<int, int>
#define F first
#define S second
using namespace std;
const int MX = 1e6 + 100;
int boss[MX], sz[MX];
int Find(int u) {
return boss[u] == u ? u : boss[u] = Find(boss[u]);
}
void merge(int a, int b) {
a = Find(a), b = Find(b);
if(a == b) return;
boss[a] = b;
sz[b] += sz[a];
}
priority_queue<int> pq[MX];
long long minimum_walk(vector<int> p, int s) {
int n = p.size();
long long sum = 0, cnt = 0;
for(int i = 0; i < n; i ++) boss[i] = i, sz[i] = 1, cnt += (i != s and p[i] == i);
for(int i = 0; i < n; i ++) sum += abs(i - p[i]), merge(i, p[i]);
vector<pair<int, pii> > E;
for(int i = 0; i + 1 < n; i ++) {
if(p[i] == i and i != s) continue;
int ptr = i + 1;
while(ptr != s and ptr < n and p[ptr] == ptr) ptr ++;
if(ptr < n) {
// cout << "E " << i << ' ' << ptr << endl;
E.push_back({ptr - i, {i, ptr}});
}
}
sort(E.begin(), E.end());
for(auto it: E) {
if(Find(it.S.F) != Find(it.S.S)) {
// cout << it.S.F << ' ' << it.S.S << endl;
merge(it.S.F, it.S.S);
sum += 2 * it.F;
}
}
// cout << cnt << ' ' << sz[Find(s)] << endl;
assert(cnt + sz[Find(s)] == n);
return sum;
}
main () {
cout << minimum_walk({1, 0, 2, 3}, 0);
}
Compilation message
books.cpp:46:7: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
main () {
^
/tmp/ccrPScG2.o: In function `main':
grader.cpp:(.text.startup+0x0): multiple definition of `main'
/tmp/ccnjtAlh.o:books.cpp:(.text.startup+0x0): first defined here
collect2: error: ld returned 1 exit status