結果

問題 No.386 貪欲な領主
ユーザー femtofemto
提出日時 2016-07-02 00:18:12
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 2,043 bytes
コンパイル時間 845 ms
コンパイル使用メモリ 78,692 KB
実行使用メモリ 23,900 KB
最終ジャッジ日時 2024-04-20 21:09:26
合計ジャッジ時間 2,038 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 AC 2 ms
6,944 KB
testcase_02 WA -
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 AC 2 ms
6,944 KB
testcase_11 AC 3 ms
6,944 KB
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
typedef long long ll;
vector<pair<int, int> > G[100000];

int N, M;
ll U[100010];
ll A[10], B[10], C[10];

class LCA {
public:
	int V, logV;
	vector<int> depth, len;
	vector<vector<int> > parent;

	LCA(int V) {
		this->V = V;
		logV = 0;
		while(V > (1LL << logV)) logV++;
		this->depth = vector<int>(V);
		this->len = vector<int>(V);
		this->parent = vector<vector<int> >(logV, vector<int>(V));
	}

	void init(int v, int par, int d, int l) {
		depth[v] = d;
		parent[0][v] = par;
		len[v] = l;
		for(int i = 0; i < (int)G[v].size(); i++) {
			int w = G[v][i].first;
			int lc = G[v][i].second;
			if(w == par) continue;
			init(w, v, d + 1, lc + l);
		}
	}

	void build() {
		for(int k = 0; k + 1 < logV; 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]];
			}
		}
	}

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

		for(int k = logV - 1; k >= 0; k--) {
			if(parent[k][u] != parent[k][v]) {
				u = parent[k][u];
				v = parent[k][v];
			}
		}
		return parent[0][u];
	}
};

ll sum[100010];

void dfs(int n, int p, ll s) {
	sum[n] = s + U[n];
	for(pair<int, int> c : G[n]) {
		if(c.first != p)
			dfs(c.first, 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(make_pair(b, 1));
		G[b].push_back(make_pair(a, 1));
	}
	LCA lca(N);
	lca.init(0, -1, 0, 0);
	lca.build();

	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++) {
		cin >> A[i] >> B[i] >> C[i];
		int cp = lca.query(A[i], B[i]);
		ans += C[i] * (sum[A[i]] + sum[B[i]] - sum[cp] * 2 + U[cp]);
	}

	cout << ans << endl;
}
0