結果

問題 No.898 tri-βutree
ユーザー kk
提出日時 2020-09-19 12:45:19
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 333 ms / 4,000 ms
コード長 1,914 bytes
コンパイル時間 2,352 ms
コンパイル使用メモリ 205,396 KB
実行使用メモリ 23,168 KB
最終ジャッジ日時 2024-04-26 09:31:07
合計ジャッジ時間 9,540 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 245 ms
23,168 KB
testcase_01 AC 4 ms
6,016 KB
testcase_02 AC 3 ms
5,888 KB
testcase_03 AC 4 ms
6,016 KB
testcase_04 AC 3 ms
5,888 KB
testcase_05 AC 3 ms
5,888 KB
testcase_06 AC 3 ms
6,016 KB
testcase_07 AC 302 ms
17,408 KB
testcase_08 AC 313 ms
17,408 KB
testcase_09 AC 304 ms
17,408 KB
testcase_10 AC 302 ms
17,536 KB
testcase_11 AC 317 ms
17,536 KB
testcase_12 AC 333 ms
17,408 KB
testcase_13 AC 317 ms
17,664 KB
testcase_14 AC 330 ms
17,536 KB
testcase_15 AC 313 ms
17,536 KB
testcase_16 AC 305 ms
17,536 KB
testcase_17 AC 315 ms
17,536 KB
testcase_18 AC 315 ms
17,536 KB
testcase_19 AC 313 ms
17,408 KB
testcase_20 AC 310 ms
17,536 KB
testcase_21 AC 324 ms
17,408 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

#define REP(i,n) for(int i=0; i<(int)(n); i++)

vector<vector<int> > doubling(const vector<int> &v) {
  int n = v.size();
  int m = 1;
  while ((1LL<<m+1) < n) ++m;
  vector<vector<int> > dp(m, vector<int>(n));
  for (int i = 0; i < n; i++) dp[0][i] = v[i];
  for (int i = 1; i < m; i++) {
    for (int j = 0; j < n; j++) {
      int tmp = dp[i-1][j];
      if (tmp == -1)
        dp[i][j] = -1;
      else
        dp[i][j] = dp[i-1][tmp];
    }
  }
  return dp;
}

int lca(int v, int w, const vector<vector<int> > &par, const vector<int> &depth) {
  if (depth[w] > depth[v])
    swap(v, w);
  
  for (int i = 0; i < par.size(); i++) {
    int d = depth[v] - depth[w];
    if (d & 1 << i) {
      v = par[i][v];
    }
  }
  
  if (v == w) return v;
  
  for (int i = par.size() - 1; i >= 0; i--) {
    if (par[i][v] != par[i][w]) {
      v = par[i][v];
      w = par[i][w];
    }
  }
  return par[0][v];
}

int n;
vector<pair<int, int> > edges[100000];
vector<int> par;
vector<int> depth;
vector<long long> weight;

void dfs(int v, int p=-1, int d=0, long long w=0) {
  par[v] = p;
  depth[v] = d;
  weight[v] = w;
  for (auto& [x, y] : edges[v]) {
    if (x == p) continue;
    dfs(x, v, d+1, w+y);
  }
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);

  cin >> n;
  
  par.resize(n);
  depth.resize(n);
  weight.resize(n);
  
  REP (i, n-1) {
    int u, v, w;
    cin >> u >> v >> w;
    edges[u].emplace_back(v, w);
    edges[v].emplace_back(u, w);
  }

  dfs(0);
  auto pp = doubling(par);

  int q;
  cin >> q;
  while (q--) {
    int x, y, z;
    cin >> x >> y >> z;
    long long ret = 0;
    ret += weight[x] + weight[y] - 2 * weight[lca(x, y, pp, depth)];
    ret += weight[y] + weight[z] - 2 * weight[lca(y, z, pp, depth)];
    ret += weight[z] + weight[x] - 2 * weight[lca(z, x, pp, depth)];
    cout << ret / 2 << endl;
  }
  
  return 0;
}
0