結果
| 問題 |
No.1094 木登り / Climbing tree
|
| ユーザー |
|
| 提出日時 | 2020-12-30 21:04:43 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
RE
|
| 実行時間 | - |
| コード長 | 1,355 bytes |
| コンパイル時間 | 1,904 ms |
| コンパイル使用メモリ | 175,044 KB |
| 実行使用メモリ | 27,520 KB |
| 最終ジャッジ日時 | 2024-10-08 02:02:49 |
| 合計ジャッジ時間 | 13,771 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 7 RE * 19 |
ソースコード
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int nax = 1e5 + 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;
}
}