結果

問題 No.898 tri-βutree
ユーザー face4face4
提出日時 2019-10-13 09:31:39
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,671 bytes
コンパイル時間 1,432 ms
コンパイル使用メモリ 73,028 KB
実行使用メモリ 23,628 KB
最終ジャッジ日時 2023-08-21 01:56:33
合計ジャッジ時間 12,646 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
typedef long long ll;

vector<int> v[100000], w[100000];
vector<ll> dist(100000, 0);
int root;

int parent[20][100000];
int depth[100000];

void dfs(int x, int p, int d){
    parent[0][x] = p;
    depth[x] = d;
    for(int i = 0; i < v[x].size(); i++){
        if(v[x][i] != p)    dist[v[x][i]] = dist[x]+w[x][i], dfs(v[x][i], x, d+1);
    }
}

void init(int n){
    dfs(root, -1, 0);
    for(int k = 0; k+1 < 20; k++){
        for(int x = 0; x < n; x++){
            if(parent[k][x] < 0)    parent[k+1][x] = -1;
            else                    parent[k+1][x] = parent[k][parent[k][x]];
        }
    }
}

int lca(int a, int b){
    if(depth[a] > depth[b]) swap(a, b);
    for(int k = 0; k < 20; k++){
        if((depth[b]-depth[a])>>k&1){
            b = parent[k][b];
        }
    }
    // 今、aとbのdepthは同じ
    if(a == b)  return a;
    for(int k = 19; k >= 0; k--){
        if(parent[k][b] != parent[k][a]){
            b = parent[k][b];
            a = parent[k][a];
        }
    }
    return parent[0][a];
}

int main(){
    int n;
    cin >> n;
    for(int i = 0; i < n-1; i++){
        int a, b, c;
        cin >> a >> b >> c;
        v[a].push_back(b);  w[a].push_back(c);
        v[b].push_back(a);  w[b].push_back(c);
    }
    init(0);
    int q;
    cin >> q;
    while(q-- > 0){
        int x[3];
        for(int i = 0; i < 3; i++)  cin >> x[i];
        ll ans = 0;
        for(int i = 0; i < 3; i++){
            int p = lca(x[i], x[(i+1)%3]);
            ans += dist[x[i]]+dist[x[(i+1)%3]]-2*dist[p];
        }
        cout << ans/2 << endl;
    }
    return 0;
}
0