제출 #953563

#제출 시각아이디문제언어결과실행 시간메모리
953563nhatcaoEvent Hopping (BOI22_events)C++14
100 / 100
317 ms25944 KiB
#include <bits/stdc++.h>
using namespace std;

const int INF = 1e9;

int main() {
    int n, q;
    cin >> n >> q; // Số lượng sự kiện và số lượng truy vấn

    vector<vector<int>> nx(17);
    vector<vector<pair<int, int>>> rmq(17);
    for (int i = 0; i < 17; i++) {
        nx[i].resize(n);
        rmq[i].resize(n, {1'000'000'001, -1});
    }

    vector<pair<int, int>> a(n);
    vector<int> b;
    for (int i = 0; i < n; i++) {
        cin >> a[i].first >> a[i].second;
        b.push_back(a[i].second);
    }

    sort(b.begin(), b.end());
    b.erase(unique(b.begin(), b.end()), b.end());

    for (int i = 0; i < n; i++) {
        int r = lower_bound(b.begin(), b.end(), a[i].second) - b.begin();
        rmq[0][r] = min(rmq[0][r], {a[i].first, i});
    }

    for (int i = 0; i + 1 < 17; i++) {
        for (int j = 0; j + (1 << (i + 1)) <= n; j++) {
            rmq[i + 1][j] = min(rmq[i][j], rmq[i][j + (1 << i)]);
        }
    }

    for (int i = 0; i < n; i++) {
        int l = lower_bound(b.begin(), b.end(), a[i].first) - b.begin();
        int r = lower_bound(b.begin(), b.end(), a[i].second) - b.begin();
        int h = 31 - __builtin_clz(r - l + 1);
        nx[0][i] = min(rmq[h][l], rmq[h][r + 1 - (1 << h)]).second;
    }

    for (int i = 0; i + 1 < 17; i++) {
        for (int j = 0; j < n; j++) {
            nx[i + 1][j] = nx[i][nx[i][j]];
        }
    }

    while (q--) {
        int x, y, l = 1;
        cin >> x >> y;
        x--, y--; // Chuyển về 0-based index

        if (x == y || (a[y].first <= a[x].second && a[x].second <= a[y].second)) {
            cout << (x == y ? 0 : 1) << "\n";
            continue;
        }

        for (int i = 16; i >= 0; i--) {
            if (a[x].second < a[nx[i][y]].first) {
                l += 1 << i;
                y = nx[i][y];
            }
        }

        y = nx[0][y];

        if (a[x].second < a[y].first || a[x].second > a[y].second) {
            cout << "impossible\n";
        } else {
            cout << l + (a[x].second >= a[y].first) << "\n";
        }
    }

    return 0;
}
#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...