結果
問題 |
No.898 tri-βutree
|
ユーザー |
|
提出日時 | 2021-04-01 23:18:29 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 1,988 ms / 4,000 ms |
コード長 | 2,874 bytes |
コンパイル時間 | 3,893 ms |
コンパイル使用メモリ | 213,016 KB |
最終ジャッジ日時 | 2025-01-20 07:21:09 |
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 21 |
ソースコード
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for(ll i=0;i<n;i++) #define repl(i,l,r) for(ll i=(l);i<(r);i++) #define per(i,n) for(ll i=(n)-1;i>=0;i--) #define perl(i,r,l) for(ll i=r-1;i>=l;i--) #define fi first #define se second #define pb push_back #define ins insert #define pqueue(x) priority_queue<x,vector<x>,greater<x>> #define all(x) (x).begin(),(x).end() #define CST(x) cout<<fixed<<setprecision(x) #define rev(x) reverse(x); using ll=long long; using vl=vector<ll>; using vvl=vector<vector<ll>>; using pl=pair<ll,ll>; using vpl=vector<pl>; using vvpl=vector<vpl>; const ll MOD=1000000007; const ll MOD9=998244353; const int inf=1e9+10; const ll INF=4e18; const ll dy[8]={-1,0,1,0,1,1,-1,-1}; const ll dx[8]={0,-1,0,1,1,-1,1,-1}; template <typename T> inline bool chmax(T &a, T b) { return ((a < b) ? (a = b, true) : (false)); } template <typename T> inline bool chmin(T &a, T b) { return ((a > b) ? (a = b, true) : (false)); } struct Edge{ ll to,weight; }; using Graph=vector<vector<Edge>>; struct LCA{ vector<vector<int>> parent; vvl dp; vector<int> dist; LCA(const Graph &G,int root=0){ int V=G.size(); int K=1; while((1<<K)<V)K++; parent.assign(K,vector<int>(V,-1)); dp.assign(K,vl(V)); dist.assign(V,-1); dfs(G,root,-1,0); for(int k=0;k+1<K;k++){ for(int v=0;v<V;v++){ if(parent[k][v]<0)continue; parent[k+1][v]=parent[k][parent[k][v]]; dp[k+1][v]=dp[k][parent[k][v]]+dp[k][v]; } } } void dfs(const Graph &G,int v,int par,int depth){ parent[0][v]=par; dist[v]=depth; for(auto p:G[v]){ if(p.to==par)continue; dfs(G,p.to,v,depth+1); dp[0][p.to]=p.weight; } } ll query(ll u,ll v){ if(dist[u]<dist[v])swap(u,v); int K=parent.size(); for(int k=0;k<K;k++){ if((dist[u]-dist[v])>>k&1){ u=parent[k][u]; } } if(u==v)return u; for(int k=K-1;k>=0;k--){ if(parent[k][u]!=parent[k][v]){ u=parent[k][u]; v=parent[k][v]; } } return parent[0][u]; } ll getsum(ll u,ll v){ if(dist[u]<dist[v])swap(u,v); int K=parent.size(); ll ret=0; for(int k=0;k<K;k++){ if((dist[u]-dist[v])>>k&1){ ret+=dp[k][u]; u=parent[k][u]; } } if(u==v)return ret; for(int k=K-1;k>=0;k--){ if(parent[k][u]!=parent[k][v]){ ret+=dp[k][u]+dp[k][v]; u=parent[k][u]; v=parent[k][v]; } } return ret+dp[0][u]+dp[0][v]; } }; int main(){ ll n;cin >> n; Graph g(n); rep(i,n-1){ ll a,b,c;cin >> a >> b >> c; g[a].push_back({b,c}); g[b].push_back({a,c}); } LCA lca(g); ll q;cin >> q; while(q--){ ll a,b,c;cin >> a >> b >> c; ll l=lca.query(a,b)^lca.query(b,c)^lca.query(c,a); cout << lca.getsum(a,l)+lca.getsum(b,l)+lca.getsum(c,l) <<endl; } }