#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];
int G[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);
G[p[i]] = max(G[p[i]], i);
G[i] = max(G[i], p[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;
if(Find(i) == Find(i + 1)) continue;
int ptr = i + 1, mx = i;
while(ptr <= G[i] or (ptr != s and ptr < n and p[ptr] == ptr)) {
if(ptr <= G[i]) mx = ptr;
if(p[ptr] == ptr) cnt --;
G[i] = max(G[i], G[ptr]);
merge(i, ptr);
ptr ++;
}
if(ptr < n) E.push_back({ptr - mx, {i, ptr}});
i = ptr - 1;
}
sort(E.begin(), E.end());
for(auto it: E) {
if(Find(it.S.F) != Find(it.S.S)) {
merge(it.S.F, it.S.S);
sum += 2 * it.F;
}
}
assert(p[0] != 0);
assert(sz[Find(s)] + cnt == n);
return sum;
}
//main () {
// cout << minimum_walk({2, 3, 0, 1}, 0);
//}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
77 ms |
63224 KB |
Execution killed with signal 11 (could be triggered by violating memory limits) |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
77 ms |
63224 KB |
Execution killed with signal 11 (could be triggered by violating memory limits) |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
77 ms |
63224 KB |
Execution killed with signal 11 (could be triggered by violating memory limits) |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
33 ms |
31736 KB |
3rd lines differ - on the 1st token, expected: '3304', found: '2744' |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
77 ms |
63224 KB |
Execution killed with signal 11 (could be triggered by violating memory limits) |
2 |
Halted |
0 ms |
0 KB |
- |