考虑刻画题目所给的两种操作。建大根笛卡尔树,则点 可以跳到自己的父亲 ,或者自己父链上第一个「变向」的点 (若 是父亲的左儿子,则可以跳到父链上第一个是父亲的右儿子的点的父亲,反之亦然)。
因此,当 , 时,有解当且仅当 是 的祖先。求答案可以优先跳 ,再跳 ,跳 的部分可以倍增,拿深度判一下有没有跳过头,跳 的部分操作次数就等于深度差。时间复杂度 。
考虑 的情况。显然,若 是 的后代, 是 的后代,则从 跳到 的操作次数一定不小于从 跳到 的操作次数。因此,把 与 的子树取交,有解当且仅当交不为空。若有解,则从区间最大值开始跳即可。求区间最大值可以用 ST 表。时间复杂度 。
考虑一般情况。先考虑判定无解。设 ,则 一定是笛卡尔树上 的最近公共祖先,因此,把 与 的子树取交,有解当且仅当交不为空。
若有解,考虑如何求答案。显然,最后一步是向右跳,且最后一步之前都应该优先把当前点的权值变大。因此从 的最大值开始跳,在不离开 的子树的前提下,优先跳 ,再跳 。如果向右跳可以一步跳到 ,则直接返回。这个过程同样可以用倍增优化,时间复杂度 。
#include <bits/stdc++.h>
using namespace std;
#define rep(i, l, r) for (int i = (l); i <= (r); ++i)
#define per(i, l, r) for (int i = (r); i >= (l); --i)
#define all(x, l, r) &(x)[l], &(x)[r] + 1
#define len(x) int((x).size())
using ll = long long;
using db = long double;
using str = string;
template <typename T>
inline bool ckmin(T& x, const T& y) {
return y < x && (x = y, true);
}
template <typename T>
inline bool ckmax(T& x, const T& y) {
return x < y && (x = y, true);
}
inline int p2(int n) { return 1 << n; }
inline int msk2(int n) { return p2(n) - 1; }
inline int msb(int n) { return n == 0 ? -1 : 31 ^ __builtin_clz(n); }
inline int bits(int n) { return 1 + msb(n - 1); }
constexpr int N = 2e5 + 5, D = 18, inf = 1e9;
int n, top;
array<int, N> h, st, fa, dep;
array<array<int, 2>, N> ch, seg;
array<array<int, N>, D> jp, far, anc, mx;
inline bool which(int x) { return x == ch[fa[x]][1]; }
int right(int x) { return fa[x] > x ? fa[x] : jp[0][x]; }
void dfs(int u, int p) {
fa[u] = p, dep[u] = dep[p] + 1;
jp[0][u] = which(u) == which(p) ? jp[0][p] : fa[p];
anc[0][u] = far[0][u] = right(u);
rep (d, 0, D - 2) {
jp[d + 1][u] = jp[d][jp[d][u]];
far[d + 1][u] = max(far[d][u], far[d][jp[d][u]]);
anc[d + 1][u] = anc[d][anc[d][u]];
}
rep (i, 0, 1) {
int v = ch[u][i];
if (v)
dfs(v, u), seg[u][i] = seg[v][i];
else
seg[u][i] = u;
}
}
inline bool cmp(int x, int y) { return h[x] < h[y]; }
void preproc() {
rep (i, 1, n) {
int old = top;
while (top && h[i] > h[st[top]]) --top;
if (old > top) ch[i][0] = st[top + 1];
if (top) ch[st[top]][1] = i;
st[++top] = i;
}
dfs(st[1], 0);
iota(all(mx[0], 1, n), 1);
rep (d, 0, D)
rep (i, 1, n - p2(d + 1) + 1)
mx[d + 1][i] = max(mx[d][i], mx[d][i + p2(d)], cmp);
}
int qmx(int l, int r) {
int d = msb(r - l + 1);
return max(mx[d][l], mx[d][r - p2(d) + 1], cmp);
}
void init(int n_, vector<int> h_) {
n = n_, copy_n(&h_[0], n, &h[1]);
preproc();
}
int minimum_jumps(int a, int b, int c, int d) {
++a, ++b, ++c, ++d;
int y = qmx(c, d);
ckmax(a, seg[y][0]), ckmin(b, seg[y][1]);
if (a > b) return -1;
int x = qmx(a, b), ans = 0;
per (d, 0, D - 1) {
if (dep[jp[d][x]] >= dep[y] && far[d][x] < c) x = jp[d][x], ans += 1 << d;
}
per (d, 0, D - 1) {
if (anc[d][x] && anc[d][x] < c) x = anc[d][x], ans += 1 << d;
}
return ans + 1;
}