結果

問題 No.1094 木登り / Climbing tree
ユーザー 37zigen37zigen
提出日時 2020-07-02 08:47:10
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 766 ms / 2,000 ms
コード長 1,379 bytes
コンパイル時間 711 ms
コンパイル使用メモリ 77,920 KB
実行使用メモリ 44,992 KB
最終ジャッジ日時 2024-04-25 18:44:17
合計ジャッジ時間 18,999 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
11,704 KB
testcase_01 AC 705 ms
33,532 KB
testcase_02 AC 216 ms
44,992 KB
testcase_03 AC 202 ms
13,876 KB
testcase_04 AC 181 ms
22,552 KB
testcase_05 AC 265 ms
32,404 KB
testcase_06 AC 410 ms
17,724 KB
testcase_07 AC 729 ms
33,532 KB
testcase_08 AC 743 ms
33,604 KB
testcase_09 AC 766 ms
33,520 KB
testcase_10 AC 742 ms
33,384 KB
testcase_11 AC 719 ms
33,396 KB
testcase_12 AC 717 ms
33,372 KB
testcase_13 AC 710 ms
33,564 KB
testcase_14 AC 719 ms
33,508 KB
testcase_15 AC 446 ms
19,164 KB
testcase_16 AC 606 ms
38,528 KB
testcase_17 AC 512 ms
26,148 KB
testcase_18 AC 495 ms
23,336 KB
testcase_19 AC 582 ms
33,892 KB
testcase_20 AC 712 ms
33,516 KB
testcase_21 AC 528 ms
28,832 KB
testcase_22 AC 742 ms
33,384 KB
testcase_23 AC 684 ms
33,360 KB
testcase_24 AC 675 ms
33,488 KB
testcase_25 AC 675 ms
33,536 KB
testcase_26 AC 684 ms
33,504 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;

vector<pair<int,int>> g[200000];
int p[200000][20];
long long cum[200000];
int dep[200000];

void dfs(int cur,int par,int d,int c) {
    cum[cur]=c;
    dep[cur]=d;
    p[cur][0]=par;
    for (auto e:g[cur]) if (e.first!=par) {
        dfs(e.first,cur,d+1,c+e.second);
    }
}

int lca(int a,int b) {
    if (a==b) return a;
    if (dep[a]<dep[b]) swap(a,b);
    if (dep[a]!=dep[b]) {
        int d=dep[a]-dep[b];
        for (int i=0;i<20;++i) {
            if ((d&(1<<i))>0) {
                a=p[a][i];
            }
        }
        return lca(a,b);
    }
    for (int i=19;i>=0;--i) {
        if (p[a][i]!=p[b][i]) {
            a=p[a][i];
            b=p[b][i];
        }
    }
    return p[a][0];
}

int main() {
    int N,Q;
    cin>>N;
    for (int i=0;i<N-1;++i) {
        int a,b,c;
        cin>>a>>b>>c;
        --a;--b;
        g[a].push_back({b,c});
        g[b].push_back({a,c});
    }
    dfs(0,-1,0,0);
    
    for (int i=1;i<20;++i) {
        for (int src=0;src<N;++src) {
            int middle=p[src][i-1];
            p[src][i]=middle==-1?middle:p[middle][i-1];
        }
    }
    
    cin>>Q;
    for (int q=0;q<Q;++q) {
        int s,t,w;
        cin>>s>>t;
        --s;--t;
        w=lca(s,t);
        long long ans=cum[s]+cum[t]-2*cum[w];
        cout<<ans<<endl;
    }
}
0