結果
| 問題 |
No.898 tri-βutree
|
| コンテスト | |
| ユーザー |
tempura_pp
|
| 提出日時 | 2019-10-04 21:34:01 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 532 ms / 4,000 ms |
| コード長 | 1,897 bytes |
| コンパイル時間 | 1,527 ms |
| コンパイル使用メモリ | 114,984 KB |
| 実行使用メモリ | 20,632 KB |
| 最終ジャッジ日時 | 2024-11-08 21:53:43 |
| 合計ジャッジ時間 | 11,202 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 21 |
ソースコード
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
using ll = long long;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;
struct LCA{
int n,h;
vector<vector<int>> par;
vector<vector<pair<int,int>>> v;
vector<ll> depth,dis;
LCA(int sz):n(sz),v(n),depth(n),dis(n){
h=1;
while((1<<h)<n)h++;
par.assign(h,vector<int>(n,-1));
}
void add_edge(int x,int y,int z){
v[x].push_back({y,z});
v[y].push_back({x,z});
}
void dfs(int x,int p,int d, ll di){
par[0][x]=p;
depth[x]=d;
dis[x]=di;
for(auto to:v[x])if(to.first!=p)dfs(to.first,x,d+1,di+to.second);
}
void build(){
dfs(0,-1,0,0);
rep(i,h-1){
rep(j,n){
if(par[i][j]<0)par[i+1][j]=-1;
else par[i+1][j]=par[i][par[i][j]];
}
}
}
int lca(int u,int v){
if(depth[u]>depth[v])swap(u,v);
rep(i,h)if((depth[v]-depth[u])>>i &1)v=par[i][v];
if(u==v)return u;
for(int i=h-1;i>=0;i--){
if(par[i][u]!=par[i][v]){
u=par[i][u];
v=par[i][v];
}
}
return par[0][u];
}
ll dist(int u,int v){
return dis[u]+dis[v]-2*dis[lca(u,v)];
}
};
int main(){
int n;
cin>>n;
LCA lca(n);
rep(i,n-1){
int x,y,z;
cin>>x>>y>>z;
lca.add_edge(x, y, z);
}
lca.build();
int q;
cin>>q;
rep(i,q){
int x,y,z;
cin>>x>>y>>z;
ll ans = longinf;
ans = min(lca.dist(x,y)+lca.dist(lca.lca(x,y),z),ans);
ans = min(lca.dist(x,z)+lca.dist(lca.lca(x,z),y),ans);
ans = min(lca.dist(z,y)+lca.dist(lca.lca(z,y),x),ans);
cout<<ans<<endl;
}
return 0;
}
tempura_pp