洛谷 P8391

如果是从左往右跳,不好决策。

不妨从右往左跳。

注意到能跳到的位置一定是一段连续的区间,所以每次跳到 \(l\) 最小的位置就可以了。

预处理后直接倍增跳,时间复杂度为 \(\mathcal O((n+q)\log n)\)

具体细节看代码。

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 @ 2022-10-10 20:39  Kobe303  阅读(33)  评论(0)    收藏  举报