結果

問題 No.898 tri-βutree
ユーザー 👑 NachiaNachia
提出日時 2020-09-27 16:12:28
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 499 ms / 4,000 ms
コード長 1,476 bytes
コンパイル時間 1,534 ms
コンパイル使用メモリ 166,948 KB
実行使用メモリ 26,240 KB
最終ジャッジ日時 2024-04-26 09:31:21
合計ジャッジ時間 11,190 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 312 ms
26,240 KB
testcase_01 AC 3 ms
5,888 KB
testcase_02 AC 4 ms
6,144 KB
testcase_03 AC 4 ms
6,016 KB
testcase_04 AC 4 ms
6,016 KB
testcase_05 AC 4 ms
5,888 KB
testcase_06 AC 4 ms
6,016 KB
testcase_07 AC 499 ms
20,352 KB
testcase_08 AC 476 ms
20,480 KB
testcase_09 AC 468 ms
20,480 KB
testcase_10 AC 460 ms
20,608 KB
testcase_11 AC 466 ms
20,352 KB
testcase_12 AC 461 ms
20,480 KB
testcase_13 AC 465 ms
20,352 KB
testcase_14 AC 464 ms
20,480 KB
testcase_15 AC 473 ms
20,352 KB
testcase_16 AC 471 ms
20,480 KB
testcase_17 AC 484 ms
20,480 KB
testcase_18 AC 473 ms
20,480 KB
testcase_19 AC 494 ms
20,352 KB
testcase_20 AC 470 ms
20,480 KB
testcase_21 AC 486 ms
20,352 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
#define rep(i,n) for(int i=0; i<(n); i++)

const int xN = 100000;

struct Edge { int to; LL dist; };

int N;
vector<Edge> E[xN];
int P[xN];
LL D[xN];
int lcaP[20][xN];
int lcaD[xN];

void dfs(int p = 0) {
    for (Edge& e : E[p]) {
        if (P[p] == e.to) continue;
        D[e.to] = D[p] + e.dist;
        lcaD[e.to] = lcaD[p] + 1;
        P[e.to] = p;
        dfs(e.to);
    }
}

void init() {
    rep(i, N) P[i] = -1;
    rep(i, N) D[i] = 0;
    dfs(0);

    rep(i, N) lcaP[0][i] = P[i];
    lcaP[0][0] = 0;
    rep(d, 19) rep(i, N) lcaP[d + 1][i] = lcaP[d][lcaP[d][i]];
}

int LCA(int u, int v) {
    if (lcaD[u] > lcaD[v]) swap(u, v);
    for (int i = 19; i >= 0; i--) if (lcaD[u] + (1 << i) <= lcaD[v]) v = lcaP[i][v];
    if (u == v) return u;
    for (int i = 19; i >= 0; i--) if (lcaP[i][u] != lcaP[i][v]) {
        u = lcaP[i][u];
        v = lcaP[i][v];
    }
    return lcaP[0][u];
}

LL distance(int u, int v) {
    int g = LCA(u, v);
    return D[u] + D[v] - 2 * D[g];
}

int main() {
    cin >> N;
    rep(i, N - 1) {
        int u, v, c; cin >> u >> v >> c;
        E[u].push_back({ v,c });
        E[v].push_back({ u,c });
    }
    init();

    int Q; cin >> Q;
    while (Q--) {
        int x, y, z; cin >> x >> y >> z;
        LL ans = distance(x, y) + distance(y, z) + distance(z, x);
        ans /= 2;
        cout << ans << endl;
    }

    return 0;
}
0