結果

問題 No.898 tri-βutree
ユーザー umezoumezo
提出日時 2022-08-12 03:49:36
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 196 ms / 4,000 ms
コード長 1,382 bytes
コンパイル時間 2,318 ms
コンパイル使用メモリ 205,700 KB
実行使用メモリ 24,916 KB
最終ジャッジ日時 2023-10-22 07:42:54
合計ジャッジ時間 8,555 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 85 ms
24,916 KB
testcase_01 AC 5 ms
13,316 KB
testcase_02 AC 5 ms
13,324 KB
testcase_03 AC 5 ms
13,324 KB
testcase_04 AC 5 ms
13,324 KB
testcase_05 AC 5 ms
13,324 KB
testcase_06 AC 5 ms
13,324 KB
testcase_07 AC 190 ms
19,116 KB
testcase_08 AC 179 ms
19,120 KB
testcase_09 AC 180 ms
19,116 KB
testcase_10 AC 180 ms
19,116 KB
testcase_11 AC 193 ms
19,112 KB
testcase_12 AC 187 ms
19,108 KB
testcase_13 AC 180 ms
19,112 KB
testcase_14 AC 182 ms
19,120 KB
testcase_15 AC 184 ms
19,116 KB
testcase_16 AC 183 ms
19,112 KB
testcase_17 AC 181 ms
19,112 KB
testcase_18 AC 177 ms
19,116 KB
testcase_19 AC 182 ms
19,116 KB
testcase_20 AC 196 ms
19,116 KB
testcase_21 AC 191 ms
19,112 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(v) v.begin(), v.end()
typedef long long ll;

#include <bits/stdc++.h>
using namespace std;

const int MAX=100010;
const int MAX_LOG=17;
vector<pair<int,ll>> G[MAX];
int root;

int parent[MAX_LOG][MAX];
int depth[MAX];
ll len[MAX];

void dfs(int v,int p,int d,ll l){
  parent[0][v]=p;
  depth[v]=d;
  len[v]=l;
  for(auto x:G[v]){
    if(x.first==p) continue;
    dfs(x.first,v,d+1,l+x.second);
  }
}

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

int lca(int u,int v){
  if(depth[u]>depth[v]) swap(u,v);
  for(int k=0;k<MAX_LOG;k++){
    if((depth[v]-depth[u])&(1<<k)) v=parent[k][v];
  }
  if(u==v) return u;
  for(int k=MAX_LOG-1;k>=0;k--){
    if(parent[k][u]!=parent[k][v]){
      u=parent[k][u];
      v=parent[k][v];
    }
  }
  return parent[0][u];
}

int main(){
  ios::sync_with_stdio(false);
  std::cin.tie(nullptr);

  int n;
  cin>>n;
  
  rep(i,n-1){
    int a,b;
    ll c;
    cin>>a>>b>>c;
    G[a].push_back({b,c});
    G[b].push_back({a,c});
  }

  root=0;
  init(n);
  
  int q;
  cin>>q;
  while(q--){
    int x,y,z;
    cin>>x>>y>>z;
    printf("%lld\n",len[x]+len[y]+len[z]-len[lca(x,y)]-len[lca(y,z)]-len[lca(x,z)]);
  }
  
  return 0;
}
0