洛谷 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;
}
posted @   Kobe303  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示