結果

問題 No.1094 木登り / Climbing tree
ユーザー 👑 kmjpkmjp
提出日時 2020-06-25 22:26:15
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 768 ms / 2,000 ms
コード長 1,562 bytes
コンパイル時間 2,168 ms
コンパイル使用メモリ 200,796 KB
実行使用メモリ 45,736 KB
最終ジャッジ日時 2024-04-25 18:32:19
合計ジャッジ時間 20,670 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 5 ms
23,088 KB
testcase_01 AC 651 ms
34,284 KB
testcase_02 AC 97 ms
45,736 KB
testcase_03 AC 191 ms
23,380 KB
testcase_04 AC 129 ms
28,252 KB
testcase_05 AC 160 ms
33,080 KB
testcase_06 AC 381 ms
26,256 KB
testcase_07 AC 655 ms
34,296 KB
testcase_08 AC 762 ms
34,548 KB
testcase_09 AC 717 ms
34,156 KB
testcase_10 AC 768 ms
34,284 KB
testcase_11 AC 767 ms
34,412 KB
testcase_12 AC 768 ms
34,284 KB
testcase_13 AC 723 ms
34,284 KB
testcase_14 AC 740 ms
34,276 KB
testcase_15 AC 432 ms
28,164 KB
testcase_16 AC 604 ms
40,816 KB
testcase_17 AC 527 ms
33,396 KB
testcase_18 AC 472 ms
31,168 KB
testcase_19 AC 599 ms
37,780 KB
testcase_20 AC 674 ms
34,420 KB
testcase_21 AC 528 ms
34,592 KB
testcase_22 AC 734 ms
34,412 KB
testcase_23 AC 749 ms
34,292 KB
testcase_24 AC 687 ms
34,284 KB
testcase_25 AC 702 ms
34,416 KB
testcase_26 AC 729 ms
34,416 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;

#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------

int N;
vector<pair<int,int>> E[200005];
int P[21][200005],D[200005];
ll AD[202020];

int Q;
int X,Y;

void dfs(int cur) {
	FORR(e,E[cur]) if(e.first!=P[0][cur]) {
		D[e.first]=D[cur]+1;
		AD[e.first]=AD[cur]+e.second;
		P[0][e.first]=cur;
		dfs(e.first);
	}
}

int lca(int a,int b) {
	int ret=0,i,aa=a,bb=b;
	if(D[aa]>D[bb]) swap(aa,bb);
	for(i=19;i>=0;i--) if(D[bb]-D[aa]>=1<<i) bb=P[i][bb];
	for(i=19;i>=0;i--) if(P[i][aa]!=P[i][bb]) aa=P[i][aa], bb=P[i][bb];
	return (aa==bb)?aa:P[0][aa];               // vertex
}

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>N;
	FOR(i,N-1) {
		cin>>x>>y>>r;
		E[x-1].push_back({y-1,r});
		E[y-1].push_back({x-1,r});
	}

	//0以外を根にするならP[0][root]=rootが必要
	dfs(0);
	FOR(i,19) FOR(x,N) P[i+1][x]=P[i][P[i][x]];
	
	cin>>Q;
	while(Q--) {
		cin>>X>>Y;
		X--,Y--;
		int lc=lca(X,Y);
		cout<<(AD[X]+AD[Y]-2*AD[lc])<<endl;
	}
	
}


int main(int argc,char** argv){
	string s;int i;
	if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
	FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
	cout.tie(0); solve(); return 0;
}
0