제출 #954444

#제출 시각아이디문제언어결과실행 시간메모리
954444TAhmed33Event Hopping (BOI22_events)C++98
100 / 100
101 ms14528 KiB
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 25;
const int B = 18;
int dp[B][MAXN];
int n, q;
array <int, 3> a[MAXN];
int jump (int a, int b) {
	for (int i = B - 1; i >= 0; i--) {
		if (b & (1 << i)) {
			a = dp[i][a];
		}
	}
	return a;
}
int idx[MAXN];
int main () {
	ios::sync_with_stdio(0); cin.tie(0);
	cin >> n >> q;
	for (int i = 1; i <= n; i++) {
		cin >> a[i][0] >> a[i][1]; a[i][2] = i;
	}
	sort(a + 1, a + n + 1, [] (array <int, 3>& x, array <int, 3>& y) {
		return x[1] == y[1] ? x[0] < y[0] : x[1] < y[1];
	});
	for (int i = 1; i <= n; i++) {
		idx[a[i][2]] = i;
	}
	vector <array <int, 3>> cur;
	for (int i = 1; i <= n; i++) {
		array <int, 3> v = {a[i][1], a[i][0], i};
		while (!cur.empty() && cur.back()[1] >= v[1]) {
			cur.pop_back();
		}
		cur.push_back(v);
		int l = 0, r = (int)cur.size() - 1, ans = -1;
		while (l <= r) {
			int mid = (l + r) / 2;
			if (cur[mid][0] >= a[i][0]) {
				r = mid - 1; ans = mid;
			} else {
				l = mid + 1;
			}
		}
		dp[0][a[i][2]] = a[cur[ans][2]][2];
	}
	for (int i = 1; i < B; i++) {
		for (int j = 1; j <= n; j++) {
			dp[i][j] = dp[i - 1][dp[i - 1][j]];
		}
	}
	while (q--) {
		int x, y; cin >> x >> y;
		//x = idx[x], y = idx[y];
		if (x == y) {
			cout << "0\n";
			continue;
		}
		int ans = 0;
		if (a[idx[y]][0] <= a[idx[x]][1]) {
			ans = -1;
		} else {
			auto l = y;
			for (int i = B - 1; i >= 0; i--) {
				auto g = dp[i][l];
				if (!g) continue;
				if (a[idx[g]][0] > a[idx[x]][1]) {
					ans ^= 1 << i;
					l = g;
				}
			}
		}
		y = jump(y, ans + 1);
		x = idx[x], y = idx[y];
		if (a[x][1] <= a[y][1] && a[x][1] >= a[y][0]) {
			cout << ans + 2 << '\n';
		} else {
			cout << "impossible\n";
		}
	}
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...