結果

問題 No.386 貪欲な領主
ユーザー femtofemto
提出日時 2016-07-11 18:26:43
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 213 ms / 2,000 ms
コード長 1,729 bytes
コンパイル時間 825 ms
コンパイル使用メモリ 71,928 KB
実行使用メモリ 28,672 KB
最終ジャッジ日時 2024-04-21 12:51:50
合計ジャッジ時間 2,815 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
5,888 KB
testcase_01 AC 4 ms
5,888 KB
testcase_02 AC 4 ms
5,888 KB
testcase_03 AC 4 ms
5,888 KB
testcase_04 AC 213 ms
28,672 KB
testcase_05 AC 185 ms
22,656 KB
testcase_06 AC 211 ms
22,656 KB
testcase_07 AC 5 ms
5,888 KB
testcase_08 AC 24 ms
7,552 KB
testcase_09 AC 5 ms
5,888 KB
testcase_10 AC 4 ms
5,760 KB
testcase_11 AC 4 ms
5,760 KB
testcase_12 AC 4 ms
5,888 KB
testcase_13 AC 8 ms
6,272 KB
testcase_14 AC 207 ms
22,656 KB
testcase_15 AC 199 ms
28,672 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;

class LCA {
public:
	vector<int> G[MAX_V];
	const int root = 0;

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

	void 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) dfs(G[v][i], v, d + 1);
		}
	}

	void init(int V) {
		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];

LCA lca;

void dfs(int n, int p, ll s) {
	sum[n] = s + U[n];
	for (int c : lca.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;
		lca.G[a].push_back(b);
		lca.G[b].push_back(a);
	}
	lca.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.lca(A, B);
		ans += C * (sum[A] + sum[B] - sum[cp] * 2 + U[cp]);
	}

	cout << ans << endl;
}
0