結果

問題 No.898 tri-βutree
ユーザー 👑 NachiaNachia
提出日時 2020-09-27 16:11:39
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
OLE  
実行時間 -
コード長 1,550 bytes
コンパイル時間 1,656 ms
コンパイル使用メモリ 168,636 KB
実行使用メモリ 28,632 KB
最終ジャッジ日時 2023-09-13 02:01:14
合計ジャッジ時間 13,228 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 OLE -
testcase_01 -- -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
権限があれば一括ダウンロードができます

ソースコード

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();

    rep(i, N) { rep(j, N) cout << distance(i, j) << " "; cout << endl; }

    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