結果
問題 | No.898 tri-βutree |
ユーザー |
![]() |
提出日時 | 2019-10-04 21:37:00 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 417 ms / 4,000 ms |
コード長 | 2,612 bytes |
コンパイル時間 | 2,570 ms |
コンパイル使用メモリ | 184,068 KB |
実行使用メモリ | 27,092 KB |
最終ジャッジ日時 | 2024-11-08 21:54:56 |
合計ジャッジ時間 | 10,587 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 21 |
ソースコード
#include <bits/stdc++.h>using namespace std;typedef long long ll;typedef pair<ll, ll> l_l;typedef pair<int, int> i_i;template<class T>inline bool chmax(T &a, T b) {if(a < b) {a = b;return true;}return false;}template<class T>inline bool chmin(T &a, T b) {if(a > b) {a = b;return true;}return false;}#define EPS (1e-7)#define INF (1e9)#define PI (acos(-1))//const ll mod = 1000000007;typedef vector<vector<ll>> Graph;template< typename G >struct DoublingLowestCommonAncestor {const int LOG;vector< int > dep;const G &g;vector< vector< int > > table;DoublingLowestCommonAncestor(const G &g) : g(g), dep(g.size()), LOG(32 - __builtin_clz(g.size())) {table.assign(LOG, vector< int >(g.size(), -1));}void dfs(int idx, int par, int d) {table[0][idx] = par;dep[idx] = d;for(auto &to : g[idx]) {if(to != par) dfs(to, idx, d + 1);}}void build() {dfs(0, -1, 0);for(int k = 0; k + 1 < LOG; k++) {for(int i = 0; i < table[k].size(); i++) {if(table[k][i] == -1) table[k + 1][i] = -1;else table[k + 1][i] = table[k][table[k][i]];}}}int query(int u, int v) {if(dep[u] > dep[v]) swap(u, v);for(int i = LOG - 1; i >= 0; i--) {if(((dep[v] - dep[u]) >> i) & 1) v = table[i][v];}if(u == v) return u;for(int i = LOG - 1; i >= 0; i--) {if(table[i][u] != table[i][v]) {u = table[i][u];v = table[i][v];}}return table[0][u];}};vector<l_l> pathes[100500];ll cost[100500];void DFS(int now, int from) {for(l_l a : pathes[now]) {if(a.first == from) continue;cost[a.first] = cost[now] + a.second;DFS(a.first, now);}}ll f(ll a, ll b, ll c) {return cost[a] + cost[b] - 2 * cost[c];}int main() {//cout.precision(10);cin.tie(0);ios::sync_with_stdio(false);int N;cin >> N;Graph G(N);for(int i = 0; i <= N - 2; i++) {ll u, v, w;cin >> u >> v >> w;G[u].push_back(v);G[v].push_back(u);pathes[u].push_back({v, w});pathes[v].push_back({u, w});}DoublingLowestCommonAncestor<Graph> LCA(G);LCA.build();DFS(0, -1);ll Q;cin >> Q;while(Q--) {ll x, y, z;cin >> x >> y >> z;ll ans = 0;ans += f(x, y, LCA.query(x, y));ans += f(z, y, LCA.query(z, y));ans += f(x, z, LCA.query(x, z));ans /= 2;cout << ans << endl;}return 0;}