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 <bits/stdc++.h>
#include "jumps.h"
using namespace std;
const int MAX_N = 2e5 + 5;
const int INF = 1e9 + 7;
int N;
int H[MAX_N];
int L[MAX_N], R[MAX_N], nxt[2][MAX_N][20];
int table[MAX_N][20];
void init(int n, vector <int> h) {
N = n;
for(int i = 1; i <= N; i++) {
H[i] = h[i - 1];
table[i][0] = H[i];
}
for(int j = 1; j < 20; j++) {
for(int i = 1; i + (1<<j) - 1 <= N; i++) {
table[i][j] = max(table[i][j - 1], table[i + (1<<(j - 1))][j - 1]);
}
}
stack <int> stk;
for(int i = 1; i <= N; i++) {
while(!stk.empty() and H[stk.top()] < H[i]) {
stk.pop();
}
if(!stk.empty()) {
L[i] = stk.top();
}
stk.push(i);
}
while(!stk.empty()) {
stk.pop();
}
for(int i = N; i >= 1; i--) {
while(!stk.empty() and H[stk.top()] < H[i]) {
stk.pop();
}
if(!stk.empty()) {
R[i] = stk.top();
}
stk.push(i);
}
for(int i = 1; i <= N; i++) {
if(L[i] == 0 and R[i] != 0) {
nxt[0][H[i]][0] = nxt[1][H[i]][0] = H[R[i]];
}
else if(L[i] != 0 and R[i] == 0) {
nxt[0][H[i]][0] = nxt[1][H[i]][0] = H[L[i]];
}
else if(L[i] != 0 and R[i] != 0) {
nxt[0][H[i]][0] = min(H[L[i]], H[R[i]]);
nxt[1][H[i]][0] = max(H[L[i]], H[R[i]]);
}
for(int j = 1; j < 20; j++) {
nxt[0][H[i]][j] = nxt[0][nxt[0][H[i]][j - 1]][j - 1];
nxt[1][H[i]][j] = nxt[1][nxt[1][H[i]][j - 1]][j - 1];
}
}
}
int get_max(int l, int r) {
if(l > r) {
return 0;
}
int j = log2(r - l + 1);
return max(table[l][j], table[r - (1<<j) + 1][j]);
}
int minimum_jumps(int A, int B, int C, int D) {
A++, B++, C++, D++;
int maxLeft = get_max(A, B);
int maxMid = get_max(B + 1, C - 1);
int maxRight = get_max(C, D);
if(max(maxLeft, maxMid) > maxRight) {
return -1;
}
if(maxLeft > maxMid) {
return 1;
}
int ans = 0;
int l = A, r = B, now = 0;
while(l <= r) {
int mid = (l + r) / 2;
int mx = get_max(mid, B);
if(mx < maxRight) {
now = mx;
r = mid - 1;
}
else {
l = mid + 1;
}
}
for(int i = 19; i >= 0; i--) {
if(nxt[1][now][i] != 0 and nxt[1][now][i] < maxMid) {
now = nxt[1][now][i];
ans += (1<<i);
}
}
if(!(nxt[1][now][0] != 0 and nxt[1][now][0] < maxRight)) {
for(int i = 19; i >= 0; i--) {
if(nxt[0][now][i] != 0 and nxt[0][now][i] < maxMid) {
now = nxt[0][now][i];
ans += (1<<i);
}
}
}
return ans + 2;
}
# | 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... |