結果

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

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
5,760 KB
testcase_01 AC 3 ms
5,888 KB
testcase_02 AC 4 ms
5,760 KB
testcase_03 AC 3 ms
5,888 KB
testcase_04 AC 149 ms
28,800 KB
testcase_05 AC 118 ms
22,656 KB
testcase_06 AC 118 ms
22,636 KB
testcase_07 AC 5 ms
5,888 KB
testcase_08 AC 19 ms
7,552 KB
testcase_09 AC 6 ms
5,888 KB
testcase_10 AC 4 ms
5,888 KB
testcase_11 AC 4 ms
5,760 KB
testcase_12 AC 4 ms
5,888 KB
testcase_13 AC 5 ms
6,400 KB
testcase_14 AC 123 ms
22,612 KB
testcase_15 AC 125 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];
	int root;

	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 add_edge(int a, int b) {
		G[a].push_back(b);
		G[b].push_back(a);
	}

	void init(int V, int root = 0) {
		this->root = root;
		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.add_edge(a, b);
	}
	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