結果

問題 No.898 tri-βutree
ユーザー tonegawatonegawa
提出日時 2020-02-06 00:48:00
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 2,173 bytes
コンパイル時間 1,075 ms
コンパイル使用メモリ 107,236 KB
実行使用メモリ 190,896 KB
最終ジャッジ日時 2023-10-24 16:44:22
合計ジャッジ時間 16,967 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 418 ms
190,896 KB
testcase_01 AC 93 ms
176,516 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 <string>
#include <vector>
#include <deque>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <bitset>
#include <cmath>
#include <functional>
#include <iomanip>
#define vll vector<ll>
#define vvv vector<vvl>
#define vvi vector<vector<int> >
#define vvl vector<vector<ll> >
#define vv(a, b, c, d) vector<vector<d> >(a, vector<d>(b, c))
#define vvvl(a, b, c, d) vector<vvl>(a, vvl(b, vll (c, d)));
#define rep(c, a, b) for(ll c=a;c<b;c++)
#define re(c, b) for(ll c=0;c<b;c++)
#define all(obj) (obj).begin(), (obj).end()
typedef long long int ll;
typedef long double ld;
typedef __int128_t lll;
using namespace std;


const int MAX_V = 1000001;
vvi G = vv(MAX_V, 0, 0, int);
int root;
int parent[30][MAX_V];
vector<int> depth(MAX_V);

void dfs(int v, int p, int d){
  parent[0][v] = p, depth[v] = d;
  for(int i=0;i<G[v].size();i++) if(G[v][i] != p) dfs(G[v][i], v, d+1);
}
void init(){
  dfs(root, -1, 0);
  for(int k=0;k+1<30;k++){
    for(int v=0;v<MAX_V;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<30;k++)if((depth[v]-depth[u])>>k & 1) v = parent[k][v];
  if(u==v) return u;
  for(int k=30-1;k>=0;k--){
    if(parent[k][u] != parent[k][v]){
      u = parent[k][u];
      v = parent[k][v];
    }
  }
  return parent[0][u];
}

struct edge{ll to, cost;};
vector<vector<edge>> T(MAX_V, vector<edge>(0));
vll d(MAX_V, 0);
void calc(ll now, ll from, ll dist){
  d[now] = dist;
  for(int i=0;i<T[now].size();i++){
    if(T[now][i].to==from) continue;
    calc(T[now][i].to, now, dist + T[now][i].cost);
  }
}
int main(int argc, char const *argv[]) {
  ll a, b, c, n;std::cin >> n;
  re(i, n-1){
    std::cin >> a >> b >> c;
    G[a].push_back(b);G[b].push_back(a);
    T[a].push_back(edge{b, c});T[b].push_back(edge{a, c});
  }
  root = 0;
  init();calc(0, -1, 0);
  ll q;std::cin >> q;
  re(i, q){
    std::cin >> a >> b >> c;
    ll A = lca(a, b), B = lca(b, c), C = lca(a, c), D = lca(A, c);
    std::cout << d[a]+d[b]+d[c]-d[A]-d[B]-d[C]+d[D] << '\n';
  }

  return 0;
}
0