結果

問題 No.386 貪欲な領主
ユーザー femtofemto
提出日時 2016-07-11 18:23:54
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 155 ms / 2,000 ms
コード長 1,652 bytes
コンパイル時間 705 ms
コンパイル使用メモリ 70,756 KB
実行使用メモリ 28,716 KB
最終ジャッジ日時 2024-04-21 12:51:38
合計ジャッジ時間 2,956 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
5,760 KB
testcase_01 AC 4 ms
5,760 KB
testcase_02 AC 4 ms
5,888 KB
testcase_03 AC 4 ms
5,888 KB
testcase_04 AC 155 ms
28,716 KB
testcase_05 AC 124 ms
22,772 KB
testcase_06 AC 121 ms
22,604 KB
testcase_07 AC 4 ms
5,888 KB
testcase_08 AC 18 ms
7,552 KB
testcase_09 AC 6 ms
5,888 KB
testcase_10 AC 4 ms
5,760 KB
testcase_11 AC 4 ms
5,888 KB
testcase_12 AC 4 ms
5,888 KB
testcase_13 AC 6 ms
6,272 KB
testcase_14 AC 128 ms
22,604 KB
testcase_15 AC 133 ms
28,716 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
typedef long long ll;

const int MAX_V = 100010;
const int MAX_LOG_V = 30;

vector<int> G[MAX_V];
const int root = 0;

int parent[MAX_LOG_V][MAX_V];
int depth[MAX_V];

void lca_dfs(int v, int p, int d) {
	parent[0][v] = p;
	depth[v] = d;
	for (int i = 0; i < G[v].size(); i++) {
		if (G[v][i] != p) lca_dfs(G[v][i], v, d + 1);
	}
}

void init(int V) {
	lca_dfs(root, -1, 0);
	for (int k = 0; k + 1 < MAX_LOG_V; k++) {
		for (int v = 0; v < V; v++) {
			if (parent[k][v] < 0) parent[k + 1][v] = -1;
			else parent[k + 1][v] = parent[k][parent[k][v]];
		}
	}
}

int lca(int u, int v) {
	if (depth[u] > depth[v]) swap(u, v);
	for (int k = 0; k < MAX_LOG_V; k++) {
		if ((depth[v] - depth[u]) >> k & 1) {
			v = parent[k][v];
		}
	}
	if (u == v) return u;
	for (int k = MAX_LOG_V - 1; k >= 0; k--) {
		if (parent[k][u] != parent[k][v]) {
			u = parent[k][u];
			v = parent[k][v];
		}
	}
	return parent[0][u];
}

int N, M;
ll U[100010];
ll sum[100010];

void dfs(int n, int p, ll s) {
	sum[n] = s + U[n];
	for (int c : G[n]) {
		if (c != p)
			dfs(c, n, s + U[n]);
	}
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	cin >> N;
	for (int i = 0; i < N - 1; i++) {
		int a, b;
		cin >> a >> b;
		G[a].push_back(b);
		G[b].push_back(a);
	}
	init(N);

	for (int i = 0; i < N; i++) {
		cin >> U[i];
	}
	dfs(0, -1, 0);

	ll ans = 0;
	cin >> M;
	for (int i = 0; i < M; i++) {
		int A, B, C;
		cin >> A >> B >> C;
		int cp = lca(A, B);
		ans += C * (sum[A] + sum[B] - sum[cp] * 2 + U[cp]);
	}

	cout << ans << endl;
}
0