結果

問題 No.898 tri-βutree
ユーザー latte0119latte0119
提出日時 2019-10-04 21:44:52
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 646 ms / 4,000 ms
コード長 1,503 bytes
コンパイル時間 2,561 ms
コンパイル使用メモリ 153,520 KB
実行使用メモリ 36,020 KB
最終ジャッジ日時 2023-08-08 15:54:20
合計ジャッジ時間 14,352 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 112 ms
36,020 KB
testcase_01 AC 6 ms
22,472 KB
testcase_02 AC 6 ms
22,256 KB
testcase_03 AC 6 ms
22,388 KB
testcase_04 AC 6 ms
22,296 KB
testcase_05 AC 6 ms
22,432 KB
testcase_06 AC 6 ms
22,252 KB
testcase_07 AC 625 ms
30,052 KB
testcase_08 AC 620 ms
30,000 KB
testcase_09 AC 604 ms
30,024 KB
testcase_10 AC 605 ms
30,028 KB
testcase_11 AC 637 ms
29,992 KB
testcase_12 AC 625 ms
29,916 KB
testcase_13 AC 646 ms
30,040 KB
testcase_14 AC 622 ms
30,080 KB
testcase_15 AC 615 ms
30,156 KB
testcase_16 AC 630 ms
30,036 KB
testcase_17 AC 615 ms
30,144 KB
testcase_18 AC 608 ms
29,928 KB
testcase_19 AC 634 ms
29,928 KB
testcase_20 AC 646 ms
29,952 KB
testcase_21 AC 617 ms
30,036 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;

#define int long long

#define rep(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
typedef vector<int>vint;
typedef pair<int,int>pint;
typedef vector<pint>vpint;

template<typename A,typename B>inline void chmin(A &a,B b){if(a>b)a=b;}
template<typename A,typename B>inline void chmax(A &a,B b){if(a<b)a=b;}

int N;
int par[20][111111];
vector<pint>G[111111];
int dep[111111],cost[111111];

void dfs(int v,int p,int d,int c){
	dep[v]=d;
	par[0][v]=p;
	cost[v]=c;
	for(auto e:G[v]){
		if(e.fi==p)continue;
		dfs(e.fi,v,d+1,c+e.se);
	}
}

int lca(int u,int v){
	if(dep[u]<dep[v])swap(u,v);
	rep(i,20)if((dep[u]-dep[v])>>i&1)u=par[i][u];
	if(u==v)return u;
	for(int i=19;i>=0;i--)if(par[i][u]!=par[i][v])u=par[i][u],v=par[i][v];
	return par[0][u];
}

inline int calc(int x,int y){
	int l=lca(x,y);
	return cost[x]+cost[y]-2*cost[l];
}
signed main(){
	scanf("%lld",&N);
	rep(i,N-1){
		int a,b,c;
		scanf("%lld%lld%lld",&a,&b,&c);
		G[a].pb({b,c});
		G[b].pb({a,c});
	}

	dfs(0,-1,0,0);
	rep(i,19){
		rep(j,N){
			if(par[i][j]==-1)par[i+1][j]=-1;
			else par[i+1][j]=par[i][par[i][j]];
		}
	}

	int Q;scanf("%lld",&Q);
	while(Q--){
		vint x(3);
		rep(i,3)scanf("%lld",&x[i]);

		vpint ls;
		rep(i,3)for(int j=i+1;j<3;j++){
			int l=lca(x[i],x[j]);
			ls.pb({dep[l],l});
		}
		sort(all(ls));
		int l=ls[2].se;
		int ans=0;
		rep(i,3)ans+=calc(x[i],l);
		printf("%lld\n",ans);
	}
	return 0;
}
0