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 "jumps.h"
#include <bits/stdc++.h>
using namespace std;
const int N = 200000 + 7;
const int K = 20;
const int inf = (int) 1e9 + 7;
int n, a[N], lft[N], rgh[N], position[N];
int rmq[K][N], lg2[N];
int getmax(int l, int r) {
assert(1 <= l && l <= r && r <= n);
int k = lg2[r - l + 1];
return max(rmq[k][l], rmq[k][r - (1 << k) + 1]);
}
void init(int nn, vector<int> hh) {
n = nn;
assert(n == (int) hh.size());
for (int i = 1; i <= n; i++) {
a[i] = hh[i - 1];
position[a[i]] = i;
rmq[0][i] = a[i];
}
for (int i = 2; i <= n; i++) {
lg2[i] = 1 + lg2[i / 2];
}
for (int k = 1; (1 << k) <= n; k++) {
for (int i = 1; i + (1 << k) - 1 <= n; i++) {
rmq[k][i] = max(rmq[k - 1][i], rmq[k - 1][i + (1 << (k - 1))]);
}
}
{
vector<int> stk;
for (int i = 1; i <= n; i++) {
while (!stk.empty() && a[stk.back()] <= a[i]) stk.pop_back();
if (!stk.empty()) lft[i] = stk.back(); else lft[i] = 0;
stk.push_back(i);
}
}
{
vector<int> stk;
for (int i = n; i >= 1; i--) {
while (!stk.empty() && a[stk.back()] <= a[i]) stk.pop_back();
if (!stk.empty()) rgh[i] = stk.back(); else rgh[i] = 0;
stk.push_back(i);
}
}
for (int i = 1; i <= n; i++) {
if (lft[i]) {
assert(a[lft[i]] > a[i]);
}
if (rgh[i]) {
assert(a[rgh[i]] > a[i]);
}
}
}
int minimum_jumps(int l1, int r1, int l2, int r2) {
l1++;
r1++;
l2++;
r2++;
assert(1 <= l1 && l1 <= r1 && r1 < l2 && l2 <= r2 && r2 <= n);
int ymax = getmax(l2, r2);
l1 = max(l1, lft[position[ymax]] + 1);
int sol = inf;
for (int x = l1; x <= r1; x++) {
int p = x, cost = 0;
while (1) {
cost++;
int p2 = p;
if (l2 <= p && p <= r2) {
sol = min(sol, cost - 1);
break;
}
if (lft[p] && a[lft[p]] <= ymax && a[lft[p]] > a[p2]) p2 = lft[p];
if (rgh[p] && a[rgh[p]] <= ymax && a[rgh[p]] > a[p2]) p2 = rgh[p];
assert(p != p2);
p = p2;
}
}
if (sol == inf) {
sol = -1;
}
return sol;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |