結果

問題 No.1094 木登り / Climbing tree
ユーザー Mr.SpockMr.Spock
提出日時 2020-12-30 21:04:43
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
RE  
実行時間 -
コード長 1,355 bytes
コンパイル時間 1,753 ms
コンパイル使用メモリ 170,752 KB
実行使用メモリ 27,520 KB
最終ジャッジ日時 2024-04-16 21:36:50
合計ジャッジ時間 12,929 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 17 ms
18,432 KB
testcase_01 RE -
testcase_02 RE -
testcase_03 AC 198 ms
18,824 KB
testcase_04 AC 163 ms
21,504 KB
testcase_05 RE -
testcase_06 AC 397 ms
20,736 KB
testcase_07 RE -
testcase_08 RE -
testcase_09 RE -
testcase_10 RE -
testcase_11 RE -
testcase_12 RE -
testcase_13 RE -
testcase_14 RE -
testcase_15 AC 343 ms
22,656 KB
testcase_16 RE -
testcase_17 AC 380 ms
26,880 KB
testcase_18 AC 363 ms
24,832 KB
testcase_19 RE -
testcase_20 RE -
testcase_21 AC 384 ms
27,520 KB
testcase_22 RE -
testcase_23 RE -
testcase_24 RE -
testcase_25 RE -
testcase_26 RE -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int nax = 1e5 + 7;
vector<pair<int, int>>edge[nax];
vector<vector<int>>dp(nax, vector<int>(22));
vector<int>tin(nax, 0);
vector<int>tout(nax, 0);
vector<int>dp1(nax, 0);
int timer;
void dfs(int child, int par) {
	tin[child] = timer++;
	dp[child][0] = par;
	for (int i = 1; i < 20; i++) {
		dp[child][i] = dp[dp[child][i - 1]][i - 1];
	}
	for (auto k : edge[child]) {
		if (k.first != par) {
			dp1[k.first] = k.second + dp1[child];
			dfs(k.first, child);
		}
	}
	tout[child] = timer++;
}
bool isancesstor(int u, int v) {
	return (tin[v] >= tin[u] && tout[u] >= tout[v]);
}
int lca(int u, int v) {
	if (isancesstor(u, v))return u;
	if (isancesstor(v, u))return v;
	for (int i = 19; i >= 0; i--) {
		if (!isancesstor(dp[u][i], v)) {
			u = dp[u][i];
		}
	}
	return dp[u][0];
}
int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n;
	cin >> n;
	for (int i = 0; i < (n - 1); i++) {
		int x, y, val;
		cin >> x >> y >> val;
		edge[x].push_back({y, val});
		edge[y].push_back({x, val});
	}
	dfs(1, 0);
	tout[0] = 1e9;
	int q;
	cin >> q;
	// for (int i = 1; i <= n; i++) {
	// 	cout << dp1[i] << " ";
	// }
	// cout << endl;
	for (int i = 0; i < q; i++) {
		int x, y;
		cin >> x >> y;
		int get_lca = lca(x, y);
		cout << dp1[x] + dp1[y] - 2 * dp1[get_lca] << endl;
	}
}
0