#include "books.h"
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int crit_l, crit_r, cmp_cnt;
int cmp[1000000], cmp_l[1000000], cmp_r[1000000];
map<pair<int, int>, ll> dp;
void extend(int &l, int &r) {
int ext_l = min(cmp_l[cmp[l]], cmp_l[cmp[r]]);
int ext_r = max(cmp_r[cmp[l]], cmp_r[cmp[r]]);
while (l != ext_l || r != ext_r) {
while (l != ext_l) {
l--;
ext_l = min(ext_l, cmp_l[cmp[l]]);
ext_r = max(ext_r, cmp_r[cmp[l]]);
}
while (r != ext_r) {
r++;
ext_l = min(ext_l, cmp_l[cmp[r]]);
ext_r = max(ext_r, cmp_r[cmp[r]]);
}
}
}
ll compute(int l, int r) {
if (dp.count({l, r})) return dp[{l, r}];
ll ans = LLONG_MAX;
if (l != crit_l) {
int nl = l - 1, nr = r;
extend(nl, nr);
ans = min(ans, compute(nl, nr) + 2);
}
if (r != crit_r) {
int nl = l, nr = r + 1;
extend(nl, nr);
ans = min(ans, compute(nl, nr) + 2);
}
return dp[{l, r}] = ans;
}
ll minimum_walk(vector<int> p, int s) {
fill(cmp, cmp + p.size(), -1);
cmp_cnt = 0, crit_l = s, crit_r = s;
ll intra = 0;
for (int i : p) {
intra += abs(p[i] - i);
if (cmp[i] == -1) {
int curr = i, sz = 0;
cmp_l[cmp_cnt] = cmp_r[cmp_cnt] = i;
do {
cmp[curr] = cmp_cnt;
cmp_l[cmp_cnt] = min(cmp_l[cmp_cnt], curr);
cmp_r[cmp_cnt] = max(cmp_r[cmp_cnt], curr);
curr = p[curr];
sz++;
} while (curr != i);
if (sz != 1) {
crit_l = min(crit_l, cmp_l[cmp_cnt]);
crit_r = max(crit_r, cmp_r[cmp_cnt]);
}
cmp_cnt++;
}
}
dp[{crit_l, crit_r}] = 0;
return intra + compute(s, s);
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Correct |
1 ms |
364 KB |
Output is correct |
3 |
Incorrect |
1 ms |
364 KB |
3rd lines differ - on the 1st token, expected: '8', found: '10' |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Correct |
1 ms |
364 KB |
Output is correct |
3 |
Incorrect |
1 ms |
364 KB |
3rd lines differ - on the 1st token, expected: '8', found: '10' |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Correct |
1 ms |
364 KB |
Output is correct |
3 |
Incorrect |
1 ms |
364 KB |
3rd lines differ - on the 1st token, expected: '8', found: '10' |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
43 ms |
7084 KB |
3rd lines differ - on the 1st token, expected: '3304', found: '3306' |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Correct |
1 ms |
364 KB |
Output is correct |
3 |
Incorrect |
1 ms |
364 KB |
3rd lines differ - on the 1st token, expected: '8', found: '10' |
4 |
Halted |
0 ms |
0 KB |
- |