結果
問題 | No.1094 木登り / Climbing tree |
ユーザー |
|
提出日時 | 2020-06-27 00:05:14 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 620 ms / 2,000 ms |
コード長 | 2,329 bytes |
コンパイル時間 | 2,590 ms |
コンパイル使用メモリ | 184,268 KB |
実行使用メモリ | 60,336 KB |
最終ジャッジ日時 | 2024-11-08 06:09:27 |
合計ジャッジ時間 | 17,670 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 26 |
ソースコード
#include <bits/stdc++.h>using namespace std;using ll = long long;using P = pair<int, ll>;constexpr char newl = '\n';struct LCA {using Graph = vector< vector<int> >;const Graph& g;const int LOGV;const int root;vector< vector<int> > parent;vector<int> depth;LCA(const Graph& g, int root = 0) : g(g), LOGV(32 - __builtin_clz(g.size())), root(root) {int V = g.size();parent.resize(LOGV, vector<int>(V));depth.resize(V);dfs(root, -1, 0);for (int k = 0; k + 1 < LOGV; k++) {for (int v = 0; v < V; v++) {if (parent[k][v] < 0) parent[k + 1][v] = -1;else parent[k + 1][v] = parent[k][parent[k][v]];}}}void dfs(int v, int p, int d) {parent[0][v] = p;depth[v] = d;for (int i : g[v]) {if (i != p) dfs(i, v, d + 1);}}int operator()(int u, int v) const {if (depth[u] > depth[v]) swap(u, v);for (int k = 0; k < LOGV; k++) {if ((depth[v] - depth[u]) >> k & 1) {v = parent[k][v];}}if (u == v) return u;for (int k = LOGV - 1; k >= 0; k--) {if (parent[k][u] != parent[k][v]) {u = parent[k][u];v = parent[k][v];}}return parent[0][u];}};using GraphW = vector< vector<P> >;void dfs(int cur, int par, const GraphW& g, vector<ll>& d) {for (const P& p : g[cur]) {if (p.first == par) continue;d[p.first] = d[cur] + p.second;dfs(p.first, cur, g, d);}}int main() {cin.tie(nullptr);ios::sync_with_stdio(false);int n;cin >> n;LCA::Graph g(n);GraphW g2(n);for (int i = 1; i < n; i++) {int a, b;ll c;cin >> a >> b >> c;--a; --b;g[a].push_back(b);g[b].push_back(a);g2[a].emplace_back(b, c);g2[b].emplace_back(a, c);}LCA lca(g);vector<ll> d(n, 0);dfs(0, -1, g2, d);int q;cin >> q;for (int i = 0; i < q; i++) {int s, t;cin >> s >> t;--s; --t;int l = lca(s, t);cout << d[s] + d[t] - d[l] * 2 << newl;}return 0;}