結果

問題 No.1094 木登り / Climbing tree
ユーザー SSRS
提出日時 2021-12-19 17:15:29
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 1,585 bytes
コンパイル時間 1,998 ms
コンパイル使用メモリ 182,168 KB
実行使用メモリ 41,400 KB
最終ジャッジ日時 2024-09-15 14:39:38
合計ジャッジ時間 27,618 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 25 WA * 1
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
const int LOG = 17;
int main(){
  int N;
  cin >> N;
  vector<vector<pair<int, int>>> E(N);
  for (int i = 0; i < N - 1; i++){
    int a, b, c;
    cin >> a >> b >> c;
    a--;
    b--;
    E[a].push_back(make_pair(c, b));
    E[b].push_back(make_pair(c, a));
  }
  vector<int> p(N, -1);
  vector<vector<int>> c(N);
  vector<int> d1(N, 0);
  vector<int> d2(N, 0);
  queue<int> q;
  q.push(0);
  while (!q.empty()){
    int v = q.front();
    q.pop();
    for (auto P : E[v]){
      int w = P.second;
      if (w != p[v]){
        p[w] = v;
        c[v].push_back(w);
        d1[w] = d1[v] + 1;
        d2[w] = d2[v] + P.first;
        q.push(w);
      }
    }
  }
  vector<vector<int>> pp(LOG, vector<int>(N, -1));
  pp[0] = p;
  for (int i = 0; i < LOG - 1; i++){
    for (int j = 0; j < N; j++){
      if (pp[i][j] != -1){
        pp[i + 1][j] = pp[i][pp[i][j]];
      }
    }
  }
  int Q;
  cin >> Q;
  for (int i = 0; i < Q; i++){
    int s, t;
    cin >> s >> t;
    s--;
    t--;
    int ans = 0;
    if (d1[s] > d1[t]){
      swap(s, t);
    }
    for (int j = 0; j < LOG; j++){
      if (((d1[t] - d1[s]) >> j & 1) == 1){
        ans += d2[t] - d2[pp[j][t]];
        t = pp[j][t];
      }
    }
    if (s != t){
      for (int j = LOG - 1; j >= 0; j--){
        if (pp[j][s] != pp[j][t]){
          ans += d2[s] - d2[pp[j][s]];
          ans += d2[t] - d2[pp[j][t]];
          s = pp[j][s];
          t = pp[j][t];
        }
      }
      ans += d2[s] - d2[p[s]];
      ans += d2[t] - d2[p[t]];
    }
    cout << ans << endl;
  }
}
0