洛谷 P8391
如果是从左往右跳,不好决策。
不妨从右往左跳。
注意到能跳到的位置一定是一段连续的区间,所以每次跳到 l 最小的位置就可以了。
预处理后直接倍增跳,时间复杂度为 O((n+q)logn)。
具体细节看代码。
Code:
#include <bits/stdc++.h>
using namespace std;
const int N = 100005, M = 200005;
int n, t, Q;
int l[N], r[N], f[N][17];
int _[M], tot;
vector <int> a[M], b[M];
int c[M];
int Min(int x, int y) { return l[x] < l[y] ? x : y; }
void upd(int x, int y) { for (; x <= tot; x += x & -x) c[x] = Min(c[x], y); }
int query(int x) { int res = 0; for (; x; x -= x & -x) res = Min(res, c[x]); return res; }
int main() {
scanf("%d%d", &n, &Q), t = log2(n);
for (int i = 1; i <= n; ++i) scanf("%d%d", &l[i], &r[i]), _[++tot] = l[i], _[++tot] = r[i];
sort(_ + 1, _ + tot + 1), tot = unique(_ + 1, _ + tot + 1) - (_ + 1);
for (int i = 1; i <= n; ++i) {
l[i] = lower_bound(_ + 1, _ + tot + 1, l[i]) - _, r[i] = lower_bound(_ + 1, _ + tot + 1, r[i]) - _;
a[l[i]].push_back(i), b[r[i]].push_back(i);
}
l[0] = 1919810;
for (int i = tot; i; --i) {
for (int x : b[i]) upd(i, x);
for (int x : a[i]) f[x][0] = query(r[x]);
}
for (int j = 1; j <= t; ++j)
for (int i = 1; i <= n; ++i)
f[i][j] = f[f[i][j - 1]][j - 1];
while (Q--) {
int x, y; scanf("%d%d", &x, &y);
if (r[x] > r[y]) printf("impossible\n");
else if (x == y) printf("%d\n", 0);
else {
int ans = 1;
for (int i = t; ~i; --i) if (l[f[y][i]] > r[x]) ans += 1 << i, y = f[y][i];
if (l[f[y][0]] > r[x]) { printf("impossible\n"); continue; }
if (l[y] > r[x]) ++ans;
printf("%d\n", ans);
}
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话