結果

問題 No.1094 木登り / Climbing tree
ユーザー KKT89
提出日時 2020-06-27 10:51:51
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 904 ms / 2,000 ms
コード長 1,938 bytes
コンパイル時間 1,060 ms
コンパイル使用メモリ 97,564 KB
最終ジャッジ日時 2025-01-11 12:40:15
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <set>
using namespace std;
typedef long long int ll;

struct LowestCommonAncester{
    int n,h;
    vector<vector<int>> g,par;
    vector<int> dep;
    LowestCommonAncester(int n):n(n),g(n),dep(n){
        h=1;
        while((1<<h)<=n)h++;
        par.assign(h,vector<int> (n,-1));
    }
    void add_edge(int u,int v){
        g[u].push_back(v);
        g[v].push_back(u);
    }
    void dfs(int v,int p,int d){
        par[0][v]=p;
        dep[v]=d;
        for(auto u:g[v]){
            if(u!=p)dfs(u,v,d+1);
        }
    }
    void build(int r){
        dfs(r,-1,0);
        for(int i=0;i<h-1;i++){
            for(int j=0;j<n;j++){
                if(par[i][j]>=0)par[i+1][j]=par[i][par[i][j]];
            }
        }
    }
    int lca(int u,int v){
        if(dep[u]>dep[v])swap(u,v);
        for(int i=0;i<h;i++){
            if((dep[v]-dep[u])&1<<i)v=par[i][v];
        }
        if(u==v)return u;
        for(int i=h-1;i>=0;i--){
            if(par[i][u]!=par[i][v])u=par[i][u],v=par[i][v];
        }
        return par[0][u];
    }
    int distance(int u,int v){
        return dep[u]+dep[v]-dep[lca(u,v)]*2;
    }
};

vector<pair<int,int>> g[200200];
int d[200200];

void dfs(int s,int p){
    for(auto t:g[s]){
        if(t.first==p)continue;
        d[t.first]=d[s]+t.second;
        dfs(t.first,s);
    }
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n; cin >> n;
    LowestCommonAncester LCA(n);
    for(int i=1;i<n;i++){
        int a,b,c; cin >> a >> b >> c;
        a--; b--;
        g[a].push_back({b,c});
        g[b].push_back({a,c});
        LCA.add_edge(a,b);
    }
    LCA.build(0);
    dfs(0,-1);
    int q; cin >> q;
    while(q--){
        int s,t; cin >> s >> t;
        s--; t--;
        int l=LCA.lca(s,t);
        cout << d[s]+d[t]-2*d[l] << endl;
    }
}
0