結果

問題 No.898 tri-βutree
ユーザー みずくらげみずくらげ
提出日時 2019-10-05 01:42:30
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 484 ms / 4,000 ms
コード長 1,906 bytes
コンパイル時間 1,432 ms
コンパイル使用メモリ 116,608 KB
実行使用メモリ 23,732 KB
最終ジャッジ日時 2023-08-08 16:11:54
合計ジャッジ時間 11,749 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 292 ms
23,732 KB
testcase_01 AC 4 ms
5,824 KB
testcase_02 AC 4 ms
5,772 KB
testcase_03 AC 3 ms
5,804 KB
testcase_04 AC 4 ms
5,812 KB
testcase_05 AC 4 ms
5,980 KB
testcase_06 AC 4 ms
5,672 KB
testcase_07 AC 474 ms
18,580 KB
testcase_08 AC 474 ms
18,584 KB
testcase_09 AC 472 ms
18,612 KB
testcase_10 AC 475 ms
18,736 KB
testcase_11 AC 475 ms
18,652 KB
testcase_12 AC 477 ms
18,732 KB
testcase_13 AC 472 ms
18,572 KB
testcase_14 AC 477 ms
18,620 KB
testcase_15 AC 476 ms
18,648 KB
testcase_16 AC 476 ms
18,652 KB
testcase_17 AC 479 ms
18,572 KB
testcase_18 AC 484 ms
18,568 KB
testcase_19 AC 474 ms
18,612 KB
testcase_20 AC 477 ms
18,616 KB
testcase_21 AC 480 ms
18,572 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <iomanip>
#include <cassert>
#include <random>
#include <tuple>

#define rep(i,n) for (int i = 0; i < (n); ++i)

using namespace std;
typedef long long ll;
typedef pair<int, int> P;

const int INF = 1001001001;


struct edge {
    int to, cost;
};

vector<edge> g[100100];

vector<int> depth;
vector<ll> cost;
vector<vector<int> > parent;

int n;

void dfs(int v, ll w=0, int p=-1, int d=0) {
    depth[v] = d;
    parent[0][v] = p;
    for (auto e: g[v]) {
        if (e.to == p) continue;
        cost[e.to] = cost[v] + e.cost;
        dfs(e.to, e.cost, v, d+1);
    }
}

void init(int root=0) {
    depth.resize(n, 0);
    cost.resize(n, 0);
    parent.resize(20, vector<int>(n, 0));
    dfs(root);
    rep(k, 19) {
        rep(v, n) {
            if (parent[k][v] < 0) parent[k+1][v] = -1;
            else parent[k+1][v] = parent[k][parent[k][v]];
        }
    }
}

int lca(int u, int v) {
    if (depth[u] > depth[v]) swap(u, v);
    rep(k, 20) {
        if (((depth[v] - depth[u]) >> k) & 1) v = parent[k][v];
    }

    if (u == v) return u;
    for (int k = 19; k >= 0; k--) {
        if (parent[k][u] == parent[k][v]) continue;
        u = parent[k][u];
        v = parent[k][v];
    }
    return parent[0][v];
}

int main() {
    cin >> n;

    rep(i, n-1) {
        int u, v, w;
        cin >> u >> v >> w;
        edge e1 = {v, w};
        g[u].push_back(e1);
        edge e2 = {u, w};
        g[v].push_back(e2);
    }

    init();

    int q;
    cin >> q;
    rep(i, q) {
        int x, y, z;
        cin >> x >> y >> z;
        int xy = lca(x, y);
        int yz = lca(y, z);
        int zx = lca(z, x);
        cout << (cost[x] + cost[y] + cost[z]  - (cost[xy] + cost[yz] + cost[zx])) << endl;
    }

    return 0;

}
0