結果

問題 No.898 tri-βutree
ユーザー noisy_noiminnoisy_noimin
提出日時 2019-10-04 21:43:17
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 413 ms / 4,000 ms
コード長 2,508 bytes
コンパイル時間 1,787 ms
コンパイル使用メモリ 181,580 KB
実行使用メモリ 29,824 KB
最終ジャッジ日時 2024-11-08 21:58:28
合計ジャッジ時間 10,058 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 21
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

using ll =  long long;
using Pll = pair<ll, ll>;
using Pii = pair<int, int>;

constexpr ll MOD = 1000000007;
constexpr long double EPS = 1e-10;
constexpr int dyx[4][2] = {
    { 0, 1}, {-1, 0}, {0,-1}, {1, 0}
};
constexpr int N_MAX = 100000;

vector<Pll> graph[N_MAX];
vector<ll> sum_cost(N_MAX, 0);

class LowestCommonAncestor {
    public:
    int root, n, LOG_V_MAX = 30;
    vector<int> depth;
    vector<vector<int>> parent;

    LowestCommonAncestor(int root=0, int n=N_MAX): root(root), n(n) {
        depth.assign(n, -1);
        parent.assign(n, vector<int>(LOG_V_MAX, -1));
        dfs(root, -1, 0);
        for(int j=1;j<LOG_V_MAX;++j) {
            for(int i=0;i<n;++i) {
                if(parent[i][j-1] == -1) continue;
                parent[i][j] = parent[parent[i][j-1]][j-1];
            }
        }
    }

    void dfs(int node, int par, int d) {
        depth[node] = d;
        parent[node][0] = par;
        for(Pll child: graph[node]) {
            int c = child.first;
            if(c == par) continue;
            dfs(c, node, d+1);
        }
    }

    int get_lca(int u, int v) {
        if(depth[u] > depth[v]) swap(u, v);
        int depth_diff = depth[v] - depth[u];
        for(int j=0;j<LOG_V_MAX;++j) {
            if(depth_diff & (1 << j)) {
                v = parent[v][j];
            }
        }
        if(u == v) return u;
        for(int j=LOG_V_MAX-1;j>=0;--j) {
            if(parent[u][j] != parent[v][j]) {
                u = parent[u][j];
                v = parent[v][j];
            }
        }
        return parent[u][0];
    }
};

void dfs_cost(int node, int par, ll s) {
    sum_cost[node] = s;
    for(Pll child: graph[node]) {
        if(child.first == par) continue;
        dfs_cost(child.first, node, s+child.second);
    }
}

inline ll calc(int x, int y, int z, LowestCommonAncestor &lca) {
    return sum_cost[x] + sum_cost[y] + sum_cost[z] - sum_cost[lca.get_lca(x, y)] - sum_cost[lca.get_lca(y, z)] - sum_cost[lca.get_lca(z, x)];
}

int main() {
    ios::sync_with_stdio(false); cin.tie(nullptr);
    int n;
    cin >> n;
    int u, v; ll w;
    for(int i=0;i<n-1;++i){
        cin >> u >> v >> w;
        graph[u].emplace_back(v, w);
        graph[v].emplace_back(u, w);
    }

    LowestCommonAncestor lca = LowestCommonAncestor(0, n);

    dfs_cost(0, -1, 0);

    int q, x, y, z;
    cin >> q;
    while(q--) {
        cin >> x >> y >> z;
        cout << calc(x, y, z, lca) << endl;
    }

}
0