結果

問題 No.2242 Cities and Teleporters
ユーザー nono00
提出日時 2023-03-11 03:08:09
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 959 ms / 3,000 ms
コード長 1,905 bytes
コンパイル時間 837 ms
コンパイル使用メモリ 86,460 KB
最終ジャッジ日時 2025-02-11 09:50:16
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>

int main() {
    int n;
    std::cin >> n;
    int log = 1;
    while ((1 << log) < n) {
        log++;
    }
    std::vector<int> h(n), t(n);
    std::vector<std::pair<int, int>> event;
    event.reserve(2 * n);
    for (int i = 0; i < n; i++) {
        std::cin >> h[i];
        event.emplace_back(h[i], ~i);
    }
    for (int i = 0; i < n; i++) {
        std::cin >> t[i];
        event.emplace_back(t[i], i);
    }
    std::sort(event.begin(), event.end());
    std::vector<std::vector<int>> parent(n, std::vector<int>(log + 1, -1));
    int max = -1;
    int max_index = -1;
    for (auto [x, i]: event) {
        // h
        if (i < 0) {
            i = ~i;
            if (max < t[i]) {
                max = t[i];
                max_index = i;
            }
        } else {
        // t
            if (x < max) {
                parent[i][0] = max_index;
            }
        }
    }

    for (int j = 0; j < log; j++) {
        for (int i = 0; i < n; i++) {
            int mid_parent = parent[i][j];
            if (mid_parent >= 0) {
                parent[i][j + 1] = parent[mid_parent][j];
            }
        }
    }

    int q;
    std::cin >> q;
    while (q--) {
        int a, b;
        std::cin >> a >> b;
        a--; b--;

        // a -> b
        // h[b] <= t[a]となるまでdoublingで上がっていく
        int count = 0;
        for (int i = log; i >= 0; i--) {
            if (parent[a][i] != -1) {
                if (t[parent[a][i]] < h[b]) {
                    a = parent[a][i];
                    count += (1 << i);
                }
            }
        }
        if (h[b] <= t[a]) {
            std::cout << 1 << '\n';
        } else if (parent[a][0] == -1) {
            std::cout << -1 << '\n';
        } else {
            std::cout << count + 2 << '\n';
        }
    }
}
0