結果
問題 | No.898 tri-βutree |
ユーザー |
![]() |
提出日時 | 2019-10-04 22:03:18 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 409 ms / 4,000 ms |
コード長 | 2,254 bytes |
コンパイル時間 | 1,989 ms |
コンパイル使用メモリ | 181,516 KB |
実行使用メモリ | 39,964 KB |
最終ジャッジ日時 | 2024-11-08 22:12:31 |
合計ジャッジ時間 | 9,771 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 21 |
ソースコード
#include<bits/stdc++.h>#define int long longusing namespace std;template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }template<class T>bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }struct edge{int to,cost;};vector<edge> G[100010];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];}};typedef vector<vector<int>> vvint;signed main(){cin.tie(0);ios::sync_with_stdio(false);int N; cin>>N;vector<vector<int>> g(N);for(int i=0;i<N-1;i++){int a,b,c; cin>>a>>b>>c;G[a].push_back({b,c});G[b].push_back({a,c});g[a].push_back(b);g[b].push_back(a);}DoublingLowestCommonAncestor<vvint> lca(g);lca.build();vector<int> depth(N);function<void(int,int)> dfs=[&](int v,int p){for(edge e:G[v]) if(e.to!=p){depth[e.to]=depth[v]+e.cost;dfs(e.to,v);}};dfs(0,-1);int Q; cin>>Q;while(Q--){int x,y,z; cin>>x>>y>>z;cout<<depth[x]+depth[y]+depth[z]-depth[lca.query(x,y)]-depth[lca.query(x,z)]-depth[lca.query(y,z)]<<endl;}// for(int i=0;i<N;i++) cout<<depth[i]<<' '; cout<<endl;return 0;}