結果

問題 No.1094 木登り / Climbing tree
ユーザー QCFiumQCFium
提出日時 2020-06-24 14:12:34
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 388 ms / 2,000 ms
コード長 1,458 bytes
コンパイル時間 1,942 ms
コンパイル使用メモリ 178,656 KB
実行使用メモリ 40,956 KB
最終ジャッジ日時 2024-04-25 18:24:38
合計ジャッジ時間 12,426 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,812 KB
testcase_01 AC 351 ms
33,368 KB
testcase_02 AC 109 ms
40,956 KB
testcase_03 AC 53 ms
6,944 KB
testcase_04 AC 84 ms
16,512 KB
testcase_05 AC 149 ms
29,420 KB
testcase_06 AC 136 ms
12,800 KB
testcase_07 AC 365 ms
33,448 KB
testcase_08 AC 364 ms
33,336 KB
testcase_09 AC 353 ms
33,340 KB
testcase_10 AC 364 ms
33,272 KB
testcase_11 AC 341 ms
33,340 KB
testcase_12 AC 378 ms
33,512 KB
testcase_13 AC 353 ms
33,476 KB
testcase_14 AC 359 ms
33,476 KB
testcase_15 AC 141 ms
11,764 KB
testcase_16 AC 274 ms
32,000 KB
testcase_17 AC 190 ms
20,516 KB
testcase_18 AC 172 ms
15,960 KB
testcase_19 AC 241 ms
27,240 KB
testcase_20 AC 347 ms
33,168 KB
testcase_21 AC 204 ms
21,552 KB
testcase_22 AC 388 ms
33,500 KB
testcase_23 AC 373 ms
33,304 KB
testcase_24 AC 362 ms
33,308 KB
testcase_25 AC 358 ms
33,356 KB
testcase_26 AC 361 ms
33,352 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

int ri() {
    int n;
    scanf("%d", &n);
    return n;
}

std::vector<std::vector<std::pair<int, int> > > hen;

std::vector<std::vector<int> > parent;
std::vector<int> dist;
std::vector<int> depth;
void dfs(int i, int prev) {
    parent[0][i] = prev;
    for (auto j : hen[i]) if (j.first != prev) {
        depth[j.first] = depth[i] + 1;
        dist[j.first] = dist[i] + j.second;
        dfs(j.first, i);
    }
}
int lca(int a, int b) {
    if (depth[a] < depth[b]) std::swap(a, b);
    for (int i = 20; i--; ) if ((depth[a] - depth[b]) >> i & 1) a = parent[i][a];
    if (a == b) return a;
    for (int i = 20; i--; ) if (parent[i][a] != parent[i][b]) a = parent[i][a], b = parent[i][b];
    return parent[0][a];
}

int main() {
    int n = ri();
    hen.resize(n);
    for (int i = 1; i < n; i++) {
        int a = ri() - 1;
        int b = ri() - 1;
        int c = ri();
        hen[a].push_back({b, c});
        hen[b].push_back({a, c});
    }
    dist.resize(n);
    depth.resize(n);
    parent.resize(20, std::vector<int> (n, -1));
    dfs(0, -1);
    for (int i = 1; i < 20; i++) for (int j = 0; j < n; j++) 
        parent[i][j] = parent[i - 1][j] == -1 ? -1 : parent[i - 1][parent[i - 1][j]];
    int q = ri();
    for (int i = 0; i < q; i++) {
        int x = ri() - 1;
        int y = ri() - 1;
        int lc = lca(x, y);
        printf("%d\n", dist[x] - dist[lc] + dist[y] - dist[lc]);
    }
    
    return 0;
}
0