結果

問題 No.898 tri-βutree
コンテスト
ユーザー zelda_master
提出日時 2026-10-21 23:27:52
言語 C++14
(gcc 15.3.0 + boost 1.92.0 + ACL)
コンパイル:
g++-15 -O2 -lm -std=c++14 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 113 ms / 4,000 ms
+ 944µs
コード長 1,624 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 407 ms
コンパイル使用メモリ 77,744 KB
実行使用メモリ 23,372 KB
最終ジャッジ日時 2026-10-21 23:28:24
合計ジャッジ時間 7,416 ms
ジャッジサーバーID
(参考情報)
judge4_0 / judge5_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 21
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

typedef long long LL;

const int N = 100010, M = 2 * N, L = 20;

LL dist[N];
int n, q, h[N], e[M], ne[M], w[M], idx, dep[N], anc[N][L];

void Add(int x, int y, int z) {
    e[idx] = y, w[idx] = z, ne[idx] = h[x], h[x] = idx++;
}

void DFS(int u, int p) {
    dep[u] = dep[p] + 1, anc[u][0] = p;
    for (int i = 1; i < L; ++i) anc[u][i] = anc[anc[u][i - 1]][i - 1];
    for (int i = h[u]; i != -1; i = ne[i]) {
        int v = e[i];
        if (v == p) continue;
        dist[v] = dist[u] + w[i];
        DFS(v, u);
    }
}

int LCA(int u, int v) {
    if (dep[u] < dep[v]) swap(u, v);
    int d = dep[u] - dep[v];
    for (int i = 0; i < L; ++i) {
        if (d >> i & 1) {
            u = anc[u][i];
        }
    }
    if (u == v) return u;
    for (int i = L - 1; i >= 0; --i) {
        if (anc[u][i] != anc[v][i]) {
            u = anc[u][i];
            v = anc[v][i];
        }
    }
    return anc[u][0];
}

LL Dist(int x, int y) {
    int lca = LCA(x, y);
    return dist[x] + dist[y] - 2 * dist[lca];
}

int main() {
    // freopen("lucky.in", "r", stdin);
    // freopen("lucky.out", "w", stdout);

    scanf("%d", &n);
    memset(h, -1, sizeof(h));
    for (int i = 1, x, y, z; i <= n - 1; ++i) {
        scanf("%d%d%d", &x, &y, &z);
        ++x, ++y;
        Add(x, y, z), Add(y, x, z);
    }
    
    DFS(1, 0);
    
    scanf("%d", &q);
    while (q--) {
        int x, y, z;
        scanf("%d%d%d", &x, &y, &z);
        ++x, ++y, ++z;
        printf("%lld\n", (Dist(x, y) + Dist(y, z) + Dist(z, x)) / 2);
    }

    return 0;
}
0