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 nx=2e5+5, kx=18;
int l[nx], r[nx], deg[nx], lvl[nx], p[kx][nx], pa[nx][kx], in[nx], out[nx], rt, t;
vector<int> d[nx], g[nx];
void dfs(int u, int p)
{
//cout<<"dfs "<<u<<'\n';
in[u]=++t;
pa[u][0]=p;
for (int i=1; i<kx; i++) pa[u][i]=pa[pa[u][i-1]][i-1];
for (auto v:g[u]) dfs(v, u);
out[u]=t;
}
void init(int N, std::vector<int> H) {
stack<int> s;
for (int i=0; i<N; i++) l[i]=r[i]=N;
for (int i=0; i<N; i++)
{
while (!s.empty()&&H[s.top()]<H[i]) s.pop();
if (!s.empty()) l[i]=s.top(), d[s.top()].push_back(i), deg[i]++;
s.push(i);
}
while (!s.empty()) s.pop();
for (int i=N-1; i>=0; i--)
{
while (!s.empty()&&H[s.top()]<H[i]) s.pop();
if (!s.empty()) r[i]=s.top(), d[s.top()].push_back(i), deg[i]++;
s.push(i);
}
queue<int> q;
for (int i=0; i<N; i++) if (l[i]==N&&r[i]==N) q.push(i), rt=i;
while (!q.empty())
{
auto u=q.front();
q.pop();
for (auto x:d[u]) if (--deg[x]==0) q.push(x);
lvl[u]=max(lvl[l[u]], lvl[r[u]])+1;
}
for (int i=0; i<N; i++)
{
if (lvl[l[i]]>lvl[r[i]]) g[l[i]].push_back(i);
else g[r[i]].push_back(i);
}
for (int i=0; i<kx; i++) p[i][N]=N;
for (int i=0; i<N; i++) p[0][i]=(lvl[l[i]]<lvl[r[i]])?l[i]:r[i];
for (int i=1; i<kx; i++) for (int j=0; j<N; j++) p[i][j]=p[i-1][p[i-1][j]];
dfs(rt, rt);
}
int minimum_jumps(int A, int B, int C, int D) {
if (A!=B) cout<<1/0;
int tmp=A;
for (int i=kx-1; i>=0; i--) if (A<=pa[tmp][i]&&pa[tmp][i]<=B) tmp=pa[tmp][i];
A=tmp;
if (!(in[D]<=in[A]&&out[A]<=out[D])) return -1;
int res=0;
for (int i=kx-1; i>=0; i--) if (lvl[p[i][A]]>=lvl[D]) res+=(1<<i), A=p[i][A];
return res+lvl[A]-lvl[D];
}
/*
7 6
3 2 1 6 4 5 7
1 2 5 5
1 2 6 6
0 3 6 6
1 4 6 6
2 3 4 4
4 5 6 6
*/
Compilation message (stderr)
jumps.cpp: In function 'int minimum_jumps(int, int, int, int)':
jumps.cpp:58:22: warning: division by zero [-Wdiv-by-zero]
58 | if (A!=B) cout<<1/0;
| ~^~| # | 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... |