結果
問題 |
No.1094 木登り / Climbing tree
|
ユーザー |
|
提出日時 | 2020-12-30 21:06:43 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 708 ms / 2,000 ms |
コード長 | 1,355 bytes |
コンパイル時間 | 2,198 ms |
コンパイル使用メモリ | 174,800 KB |
実行使用メモリ | 52,480 KB |
最終ジャッジ日時 | 2024-11-08 07:12:01 |
合計ジャッジ時間 | 19,961 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 26 |
ソースコード
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int nax = 2e5 + 7; vector<pair<int, int>>edge[nax]; vector<vector<int>>dp(nax, vector<int>(22)); vector<int>tin(nax, 0); vector<int>tout(nax, 0); vector<int>dp1(nax, 0); int timer; void dfs(int child, int par) { tin[child] = timer++; dp[child][0] = par; for (int i = 1; i < 20; i++) { dp[child][i] = dp[dp[child][i - 1]][i - 1]; } for (auto k : edge[child]) { if (k.first != par) { dp1[k.first] = k.second + dp1[child]; dfs(k.first, child); } } tout[child] = timer++; } bool isancesstor(int u, int v) { return (tin[v] >= tin[u] && tout[u] >= tout[v]); } int lca(int u, int v) { if (isancesstor(u, v))return u; if (isancesstor(v, u))return v; for (int i = 19; i >= 0; i--) { if (!isancesstor(dp[u][i], v)) { u = dp[u][i]; } } return dp[u][0]; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; for (int i = 0; i < (n - 1); i++) { int x, y, val; cin >> x >> y >> val; edge[x].push_back({y, val}); edge[y].push_back({x, val}); } dfs(1, 0); tout[0] = 1e9; int q; cin >> q; // for (int i = 1; i <= n; i++) { // cout << dp1[i] << " "; // } // cout << endl; for (int i = 0; i < q; i++) { int x, y; cin >> x >> y; int get_lca = lca(x, y); cout << dp1[x] + dp1[y] - 2 * dp1[get_lca] << endl; } }