結果

問題 No.898 tri-βutree
ユーザー tempura_pptempura_pp
提出日時 2019-10-04 21:34:01
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 514 ms / 4,000 ms
コード長 1,897 bytes
コンパイル時間 1,222 ms
コンパイル使用メモリ 113,016 KB
実行使用メモリ 20,356 KB
最終ジャッジ日時 2023-08-08 15:50:56
合計ジャッジ時間 11,581 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 308 ms
20,356 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 505 ms
17,392 KB
testcase_08 AC 502 ms
17,588 KB
testcase_09 AC 509 ms
17,336 KB
testcase_10 AC 503 ms
17,504 KB
testcase_11 AC 505 ms
17,592 KB
testcase_12 AC 510 ms
17,512 KB
testcase_13 AC 509 ms
17,336 KB
testcase_14 AC 512 ms
17,336 KB
testcase_15 AC 512 ms
17,392 KB
testcase_16 AC 502 ms
17,516 KB
testcase_17 AC 514 ms
17,408 KB
testcase_18 AC 513 ms
17,516 KB
testcase_19 AC 507 ms
17,400 KB
testcase_20 AC 499 ms
17,416 KB
testcase_21 AC 513 ms
17,732 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#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;
}
0