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;
int N;
vector<int> H;
bool subtask1;
vector<vector<int>> adj, hi, lo;
void init(int n, vector<int> h) {
N = n, H = h;
subtask1 = 1;
for (int i = 0; i < N; i++) {
H[i]--;
if (i != H[i]) {
subtask1 = 0;
}
}
adj.resize(N);
vector<int> stk;
for (int i = N - 1; i >= 0; i--) {
while (!stk.empty() && H[stk.back()] < H[i]) {
stk.pop_back();
}
if (!stk.empty()) {
adj[H[i]].push_back(H[stk.back()]);
}
stk.push_back(i);
}
stk.clear();
for (int i = 0; i < N; i++) {
while (!stk.empty() && H[stk.back()] < H[i]) {
stk.pop_back();
}
if (!stk.empty()) {
adj[H[i]].push_back(H[stk.back()]);
}
stk.push_back(i);
}
lo.resize(N + 1, vector<int>(18, N));
hi.resize(N + 1, vector<int>(18, N));
for (int i = 0; i < N; i++) {
if (adj[i].size() == 1) {
hi[i][0] = adj[i][0];
}
if (adj[i].size() == 2) {
tie(lo[i][0], hi[i][0]) = minmax(adj[i][0], adj[i][1]);
}
}
for (int j = 0; j < 17; j++) {
for (int i = 0; i < N; i++) {
lo[i][j + 1] = lo[lo[i][j]][j];
hi[i][j + 1] = hi[hi[i][j]][j];
}
}
}
int minimum_jumps(int A, int B, int C, int D) {
if (subtask1) {
return C - B;
}
if (A == B && C == D) {
int x = H[A];
int y = H[C];
int ans = 0;
for (int i = 17; i >= 0; i--) {
if (hi[x][i] <= y) {
ans += 1 << i;
x = hi[x][i];
}
}
for (int i = 17; i >= 0; i--) {
if (lo[x][i] <= y) {
ans += 1 << i;
x = lo[x][i];
}
}
if (x != y) {
ans = -1;
}
return ans;
}
vector<int> dis(N, N);
queue<int> q;
for (int i = A; i <= B; i++) {
dis[H[i]] = 0;
q.push(H[i]);
}
while (!q.empty()) {
int x = q.front();
q.pop();
for (int y : adj[x]) {
if (dis[y] == N) {
dis[y] = dis[x] + 1;
q.push(y);
}
}
}
int ans = N;
for (int i = C; i <= D; i++) {
ans = min(ans, dis[H[i]]);
}
if (ans == N) {
ans = -1;
}
return ans;
}
# | 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... |