結果
| 問題 |
No.898 tri-βutree
|
| コンテスト | |
| ユーザー |
IKyopro
|
| 提出日時 | 2019-10-04 23:58:57 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
AC
|
| 実行時間 | 487 ms / 4,000 ms |
| コード長 | 1,865 bytes |
| コンパイル時間 | 2,244 ms |
| コンパイル使用メモリ | 82,276 KB |
| 実行使用メモリ | 35,548 KB |
| 最終ジャッジ日時 | 2024-11-08 22:37:35 |
| 合計ジャッジ時間 | 11,506 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 21 |
ソースコード
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
typedef long long ll;
struct edge{
int to;
ll w;
};
class LCA{
private:
vector<vector<edge>> v;
vector<vector<int>> parent;
vector<int> depth;
void dfs(int n,int m,int d){
parent[0][n] = m;
depth[n] = d;
for(auto x:v[n]){
if(x.to!=m) dfs(x.to,n,d+1);
}
}
public:
LCA(int N,int root,vector<vector<edge>>& tree){
v = tree;
parent = vector<vector<int>>(20,vector<int>(N,0));
depth = vector<int>(N,0);
dfs(root,-1,0);
for(int j=0;j+1<20;j++){
for(int i=0;i<N;i++){
if(parent[j][i]<0) parent[j+1][i] = -1;
else parent[j+1][i] = parent[j][parent[j][i]];
}
}
}
int lca(int n,int m){
if(depth[n]>depth[m]) swap(n,m);
for(int j=0;j<20;j++){
if((depth[m]-depth[n]) >> j&1) m = parent[j][m];
}
if(n==m) return n;
for(int j=19;j>=0;j--){
if(parent[j][n]!=parent[j][m]){
n = parent[j][n];
m = parent[j][m];
}
}
return parent[0][n];
}
int dep(int n){return depth[n];}
};
int main(){
int N;
cin >> N;
vector<vector<edge>> tree(N);
for(int i=0;i<N-1;i++){
int a,b;
ll w;
cin >> a >> b >> w;
tree[a].push_back({b,w});
tree[b].push_back({a,w});
}
LCA lca(N,0,tree);
vector<ll> dist(N,0);
function<void(int,int)> dfs = [&](int cur,int par){
for(auto x:tree[cur]) if(par!=x.to) {
dist[x.to] = dist[cur] + x.w;
dfs(x.to,cur);
}
};
dfs(0,-1);
int Q;
cin >> Q;
auto ans = [&](int x,int y,int z){
ll res = 2*(dist[x]+dist[y]+dist[z]);
res -= 2*(dist[lca.lca(x,y)]+dist[lca.lca(y,z)]+dist[lca.lca(z,x)]);
return res/2;
};
for(int i=0;i<Q;i++){
int x,y,z;
cin >> x >> y >> z;
cout << ans(x,y,z) << endl;
}
}
IKyopro