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;
const int MAX = 2e3 + 5;
const int inf = 1e9;
int N, H[MAX];
vector<int> adj[MAX];
struct RMQ{
vector<vector<int>> rmq;
RMQ(vector<int>& a) : rmq(){
int N = (int)a.size();
int L = 32 - __builtin_clz(N);
rmq.emplace_back(a);
for(int i = 1; i < L; ++i){
rmq.emplace_back(N - (1 << i) + 1);
for(int j = 0; j + (1 << i) <= N; ++j){
rmq[i][j] = min(rmq[i - 1][j], rmq[i - 1][j + (1 << (i - 1))]);
}
}
}
int query(int l, int r){
int k = 31 - __builtin_clz(r - l + 1);
return min(rmq[k][l], rmq[k][r - (1 << k) + 1]);
}
};
vector<RMQ> rmqs;
vector<int> bfs(int s){
vector<int> d(N, inf);
queue<int> q;
q.push(s);
d[s] = 0;
while(!q.empty()){
int u = q.front(); q.pop();
for(auto v : adj[u]){
if(d[v] == inf){
d[v] = d[u] + 1;
q.push(v);
}
}
}
return d;
}
void init(int _N, vector<int> _H){
N = _N;
for(int i = 0; i < N; ++i) H[i] = _H[i];
stack<int> st;
for(int i = 0; i < N; ++i){
while(!st.empty() && H[st.top()] <= H[i]) st.pop();
if(!st.empty()) adj[i].emplace_back(st.top());
st.push(i);
}
stack<int>().swap(st);
for(int i = N - 1; i >= 0; --i){
while(!st.empty() && H[st.top()] <= H[i]) st.pop();
if(!st.empty()) adj[i].emplace_back(st.top());
st.push(i);
}
for(int i = 0; i < N; ++i){
vector<int> d = bfs(i);
rmqs.emplace_back(RMQ(d));
}
}
int minimum_jumps(int a, int b, int c, int d){
int best = -1, limit = -inf;
for(int i = c; i <= d; ++i){
limit = max(limit, H[i]);
}
for(int i = a; i <= b; ++i){
if(H[i] < limit && (best == -1 || H[best] < H[i])){
best = i;
}
}
if(best == -1) return -1;
int check = rmqs[best].query(c, d);
return (check == inf ? -1 : check);
}
#ifdef LOCAL
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
freopen("task.inp", "r", stdin);
freopen("task.ans", "w", stdout);
int N, Q;
cin >> N >> Q;
vector<int> H(N);
for(int i = 0; i < N; ++i){
cin >> H[i];
}
init(N, H);
for(int i = 0; i < Q; ++i){
int a, b, c, d;
cin >> a >> b >> c >> d;
cout << minimum_jumps(a, b, c, d) << '\n';
}
return 0;
}
#endif //LOCAL
# | 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... |