結果
| 問題 |
No.1094 木登り / Climbing tree
|
| ユーザー |
|
| 提出日時 | 2024-06-28 16:20:33 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 340 ms / 2,000 ms |
| コード長 | 2,639 bytes |
| コンパイル時間 | 1,817 ms |
| コンパイル使用メモリ | 171,184 KB |
| 実行使用メモリ | 50,944 KB |
| 最終ジャッジ日時 | 2024-06-28 16:20:49 |
| 合計ジャッジ時間 | 14,122 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 26 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) x.begin(),x.end()
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define rep_r(i,a,b) for(int i=a;i>=b;i--)
#define each(a,x) for (auto& x : a)
using pi = pair<int,int>;
using pl = pair<ll,ll>;
using vi = vector<int>;
using vl = vector<ll>;
#define sz(x) int(x.size())
#define so(x) sort(all(x))
#define so_r(x) sort(all(x),greater<int>())
#define lb lower_bound
#define ub upper_bound
const char nl = '\n';
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int bit_cnt(int x){
return __builtin_popcount(x);
}
ll bex(ll a, ll b, ll mod = 1e9 + 7){ll res = 1LL; while(b){ if (b&1) res = res * a % mod; a = a * a % mod; b >>= 1;} return res;}
template<class t,class u> bool chmax(t&a,u b){if(a<b){a=b;return true;}else return false;}
template<class t,class u> bool chmin(t&a,u b){if(b<a){a=b;return true;}else return false;}
const int MOD = 998244353;
const int N = 5e5 + 5;
const ll INF = 1e16;
// https://yukicoder.me/problems/no/1094
// Brief: undirected weighted tree with N vertices
// i-th edge: A <-> B with cost C
// Q queries: find cost from s[j] to t[j] in each query
// this probably use RMQ
// dist[i,j] = cost[i] + cost[j] - 2 * cost[fa[i,j]]
vector<pair<int,int>> g[N];
int cost[N];
// https://wiki.vnoi.info/algo/data-structures/lca-binlift.md
int h[N];
int up[N][20];
void dfs(int u, int fa){
each(g[u],ed){
int v = ed.first, w = ed.second;
if (v == fa) continue;
h[v] = h[u] + 1;
up[v][0] = u;
for (int j = 1; j < 20; j++){
up[v][j] = up[up[v][j-1]][j-1];
}
cost[v] = cost[u] + w;
dfs(v,u);
}
}
int lca(int u, int v){
if (h[u] != h[v]){
if (h[u] < h[v]) swap(u,v);
int k = h[u] - h[v];
for (int j = 0; (1 << j) <= k; j++){
if (k>>j&1) u = up[u][j];
}
}
if (u == v) return u;
int k = log2(h[u]);
for (int j = k; j >= 0; j--){
if (up[u][j] != up[v][j]) {
u = up[u][j];
v = up[v][j];
}
}
return up[u][0];
}
int calc(int u, int v){
int fa = lca(u,v);
return cost[u] + cost[v] - 2 * cost[fa];
}
void solve(){
int n; cin >> n;
rep(_,1,n-1){
int a,b,c;
cin >> a >> b >> c;
g[a].push_back({b,c});
g[b].push_back({a,c});
}
dfs(1,1);
int q; cin >> q;
while (q--){
int s,t; cin >> s >> t;
cout << calc(s,t) << nl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
// cin >> t;
while (t--){
solve();
}
}