結果
問題 | No.898 tri-βutree |
ユーザー |
![]() |
提出日時 | 2019-10-07 19:51:10 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 512 ms / 4,000 ms |
コード長 | 2,246 bytes |
コンパイル時間 | 2,093 ms |
コンパイル使用メモリ | 184,008 KB |
実行使用メモリ | 52,480 KB |
最終ジャッジ日時 | 2024-11-08 23:00:05 |
合計ジャッジ時間 | 12,193 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
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; }class LowestCommonAncestor{public:const int N;vector<vector<int>> G;vector<int> parent,depth;const int LOG;vector<vector<int>> dp;LowestCommonAncestor(vector<vector<int>> G):N(G.size()),G(G),parent(N),depth(N),LOG(32-__builtin_clz(N)){dfs(0,-1,0);dp.assign(LOG,vector<int>(N,-1));for(int i=0;i<N;i++) dp[0][i]=parent[i];for(int i=0;i+1<LOG;i++){for(int j=0;j<N;j++){if(dp[i][j]==-1) dp[i+1][j]=-1;else dp[i+1][j]=dp[i][dp[i][j]];}}}void dfs(int v,int p,int d){parent[v]=p;depth[v]=d;for(int u:G[v]) if(u!=p){dfs(u,v,d+1);}}int query(int u,int v){if(depth[u]>depth[v]) swap(u,v);for(int i=0;i<LOG;i++){if((depth[v]-depth[u])>>i&1) v=dp[i][v];}if(u==v) return u;for(int i=LOG-1;i>=0;i--){if(dp[i][u]!=dp[i][v]){u=dp[i][u];v=dp[i][v];}}return dp[0][u];}};struct edge{int to,cost;};signed main(){cin.tie(0);ios::sync_with_stdio(false);int N; cin>>N;vector<vector<edge>> G(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);}vector<int> dist(N);function<void(int,int)> dfs=[&](int v,int p){for(edge e:G[v]) if(e.to!=p){dist[e.to]=dist[v]+e.cost;dfs(e.to,v);}};dfs(0,-1);LowestCommonAncestor lca(g);auto calc=[&](int u,int v){return dist[u]+dist[v]-2*dist[lca.query(u,v)];};int Q; cin>>Q;while(Q--){int x,y,z; cin>>x>>y>>z;int ans=calc(x,y)+calc(y,z)+calc(z,x);ans/=2;cout<<ans<<endl;}return 0;}