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>
using namespace std;
typedef long long ll;
typedef long double ld;
const int N = 2e5 + 7;
const int L = 19;
const int INF = 1e9;
int n, h[N];
int l[N][L], r[N][L];
int big[N][L];
void build() {
for (int i = 0; i < n; ++i) {
l[i][0] = -1;
r[i][0] = -1;
big[i][0] = -1;
}
vector<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && h[st.back()] < h[i]) {
r[st.back()][0] = i;
st.pop_back();
}
st.push_back(i);
}
st.clear();
for (int i = n - 1; i >= 0; --i) {
while (!st.empty() && h[st.back()] < h[i]) {
l[st.back()][0] = i;
st.pop_back();
}
st.push_back(i);
}
st.clear();
for (int i = 0; i < n; ++i) {
if (l[i][0] != -1 && (big[i][0] == -1 || h[l[i][0]] > h[big[i][0]])) big[i][0] = l[i][0];
if (r[i][0] != -1 && (big[i][0] == -1 || h[r[i][0]] > h[big[i][0]])) big[i][0] = r[i][0];
}
for (int p = 1; p < L; ++p) {
for (int i = 0; i < n; ++i) {
l[i][p] = l[i][p - 1] == -1 ? -1 : l[l[i][p - 1]][p - 1];
r[i][p] = r[i][p - 1] == -1 ? -1 : r[r[i][p - 1]][p - 1];
big[i][p] = big[i][p - 1] == -1 ? -1 : big[big[i][p - 1]][p - 1];
}
}
}
void init(int n2, vector<int> h2) {
n = n2;
for (int i = 0; i < n2; ++i) h[i] = h2[i] - 1;
build();
}
int get_dist(int s, int t) {
int res = 0;
for (int i = L - 1; i >= 0; --i) {
if (big[s][i] != -1 && h[big[s][i]] <= h[t]) {
res += (1 << i);
s = big[s][i];
}
}
for (int i = L - 1; i >= 0; --i) {
if (r[s][i] != -1 && h[r[s][i]] <= h[t]) {
res += (1 << i);
s = r[s][i];
}
}
return s == t ? res : INF;
}
int minimum_jumps(int A, int B, int C, int D) {
int a = A, b = B, c = C, d = D;
int res = INF;
for (int s = a; s <= b; ++s) {
for (int t = c; t <= d; ++t) res = min(res, get_dist(s, t));
}
return res == INF ? -1 : res;
}
#ifdef LOCAL
int main() {
freopen("input.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(0);
int n2, q2;
cin >> n2 >> q2;
vector<int> h2(n2);
for (auto &i : h2) cin >> i;
init(n2, h2);
while (q2--) {
int A, B, C, D;
cin >> A >> B >> C >> D;
cout << minimum_jumps(A, B, C, D) << endl;
}
return 0;
}
#endif
# | 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... |