結果

問題 No.898 tri-βutree
ユーザー totori_nyaatotori_nyaa
提出日時 2020-02-08 03:24:33
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,999 bytes
コンパイル時間 3,915 ms
コンパイル使用メモリ 173,188 KB
実行使用メモリ 31,832 KB
最終ジャッジ日時 2023-10-26 00:37:18
合計ジャッジ時間 8,615 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 93 ms
31,832 KB
testcase_01 AC 6 ms
9,828 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<bits/stdc++.h>
using namespace std;
typedef long long ll;


// LCA
// verify: https://atcoder.jp/contests/abc014/submissions/9535352
vector<vector<array<ll,2>>> v(200010);
bool used[200010];
int depth[200010];
int par[200010][20];
ll dp[200020];

// 根からの深さと1つ上の親を求める. initの中で使う
void dfs(int p,int d,ll cost){
    used[p] = 1;
    depth[p] = d;
    dp[p]=cost;
    for(auto i:v[p]){
        if(!used[i[0]]){
            dfs(i[0],d+1,cost+i[1]);
            par[i[0]][0] = p;
        }
    }
}

// init(n, root) でダブリングテーブルを作製する, nは頂点数
void init(int n,int root=0){
    for(int i=0;i<n;i++){
        used[i]=false;
        for(int j=0;j<20;j++){
            par[i][j] = -1;
        }
    }
    dfs(root,0,0);
    for(int j=1;j<20;j++){
        for(int i=0;i<n;i++){
            if(par[i][j-1] == -1) continue;
            par[i][j] = par[par[i][j-1]][j-1];
        }
    }
}

//頂点aのd個上の親を求める
ll get_nyaa(ll a,ll d){
    for(ll i=19;i>=0;i--){
        if(d & (1<<i)) a = par[a][i];
    }
    return a;
}

// a,bのLCAを求める
int lca(int a,int b){
    if(depth[a] < depth[b]) swap(a,b);
    int dif = depth[a] - depth[b];
    for(int i=19;i>=0;i--){
        if(dif & (1<<i)) a = par[a][i];
    }
    if(a==b) return a;
    for(int i=19;i>=0;i--){
        if(par[a][i]!=par[b][i]){
            a = par[a][i], b = par[b][i];
        }
    }
    return par[a][0];
}

signed main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(20);
 
    ll n;
    cin>>n;
    for(int i=1;i<n;i++){
        ll a,b,c;
        cin>>a>>b>>c;
        v[b].push_back({a,c});
        v[a].push_back({b,c});
    }
    init(n);
    int q; cin>>q;
    while(q--){
        int a,b,c;
        cin>>a>>b>>c;
        ll ans = dp[a] + dp[b] + dp[c];
        ans -= dp[lca(a,b)] + dp[lca(a,c)] + dp[lca(b,c)];
        ans += dp[lca(a,lca(b,c))];
        cout << ans << "\n";
    }

    
}
0