結果
問題 | No.1094 木登り / Climbing tree |
ユーザー | tkmst201 |
提出日時 | 2021-02-11 18:41:33 |
言語 | C++17 (gcc 12.3.0 + boost 1.83.0) |
結果 |
AC
|
実行時間 | 388 ms / 2,000 ms |
コード長 | 1,626 bytes |
コンパイル時間 | 2,471 ms |
コンパイル使用メモリ | 206,172 KB |
実行使用メモリ | 42,784 KB |
最終ジャッジ日時 | 2024-04-25 19:36:15 |
合計ジャッジ時間 | 13,700 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 2 ms
6,812 KB |
testcase_01 | AC | 388 ms
31,144 KB |
testcase_02 | AC | 106 ms
42,784 KB |
testcase_03 | AC | 49 ms
6,944 KB |
testcase_04 | AC | 85 ms
15,444 KB |
testcase_05 | AC | 161 ms
27,552 KB |
testcase_06 | AC | 134 ms
11,992 KB |
testcase_07 | AC | 383 ms
31,140 KB |
testcase_08 | AC | 381 ms
31,008 KB |
testcase_09 | AC | 387 ms
31,136 KB |
testcase_10 | AC | 377 ms
31,144 KB |
testcase_11 | AC | 370 ms
31,140 KB |
testcase_12 | AC | 371 ms
31,016 KB |
testcase_13 | AC | 369 ms
31,140 KB |
testcase_14 | AC | 386 ms
31,012 KB |
testcase_15 | AC | 126 ms
12,032 KB |
testcase_16 | AC | 277 ms
33,324 KB |
testcase_17 | AC | 179 ms
21,148 KB |
testcase_18 | AC | 150 ms
16,572 KB |
testcase_19 | AC | 238 ms
28,440 KB |
testcase_20 | AC | 372 ms
31,144 KB |
testcase_21 | AC | 194 ms
22,580 KB |
testcase_22 | AC | 382 ms
31,140 KB |
testcase_23 | AC | 369 ms
31,012 KB |
testcase_24 | AC | 362 ms
31,140 KB |
testcase_25 | AC | 368 ms
31,144 KB |
testcase_26 | AC | 371 ms
31,268 KB |
ソースコード
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) begin(v),end(v) template<typename A, typename B> inline bool chmax(A & a, const B & b) { if (a < b) { a = b; return true; } return false; } template<typename A, typename B> inline bool chmin(A & a, const B & b) { if (a > b) { a = b; return true; } return false; } using ll = long long; using pii = pair<int, int>; constexpr ll INF = 1ll<<30; constexpr ll longINF = 1ll<<60; constexpr ll MOD = 1000000007; constexpr bool debug = false; //---------------------------------// int main() { int N; cin >> N; vector<vector<pii>> g(N); REP(i, N - 1) { int a, b, c; scanf("%d %d %d", &a, &b, &c); --a; --b; g[a].emplace_back(b, c); g[b].emplace_back(a, c); } vector par(18, vector<int>(N, -1)); vector<int> dist(N), depth(N); auto dfs = [&](auto self, int u) -> void { for (auto [v, d] : g[u]) if (v != par[0][u]) { dist[v] = dist[u] + d; depth[v] = depth[u] + 1; par[0][v] = u; self(self, v); } }; par[0][0] = 0; dfs(dfs, 0); FOR(i, 1, 18) REP(j, N) par[i][j] = par[i - 1][par[i - 1][j]]; int Q; cin >> Q; while (Q--) { int s, t; scanf("%d %d", &s, &t); --s; --t; if (depth[s] < depth[t]) swap(s, t); const int d = depth[s] - depth[t]; int a = s, b = t; REP(i, 18) if (d >> i & 1) a = par[i][a]; int lca; if (a == b) lca = a; else { for (int i = 17; i >= 0; --i) if (par[i][a] != par[i][b]) a = par[i][a], b = par[i][b]; lca = par[0][a]; } int ans = dist[s] - 2 * dist[lca] + dist[t]; printf("%d\n", ans); } }