結果
問題 | No.386 貪欲な領主 |
ユーザー | pekempey |
提出日時 | 2016-07-01 22:53:07 |
言語 | C++11 (gcc 11.4.0) |
結果 |
AC
|
実行時間 | 232 ms / 2,000 ms |
コード長 | 1,777 bytes |
コンパイル時間 | 1,322 ms |
コンパイル使用メモリ | 151,148 KB |
実行使用メモリ | 30,516 KB |
最終ジャッジ日時 | 2023-08-02 08:55:31 |
合計ジャッジ時間 | 3,485 ms |
ジャッジサーバーID (参考情報) |
judge12 / judge15 |
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 3 ms
5,780 KB |
testcase_01 | AC | 4 ms
5,788 KB |
testcase_02 | AC | 3 ms
5,792 KB |
testcase_03 | AC | 3 ms
5,856 KB |
testcase_04 | AC | 232 ms
30,516 KB |
testcase_05 | AC | 184 ms
24,556 KB |
testcase_06 | AC | 198 ms
24,276 KB |
testcase_07 | AC | 4 ms
5,884 KB |
testcase_08 | AC | 23 ms
7,516 KB |
testcase_09 | AC | 5 ms
6,000 KB |
testcase_10 | AC | 3 ms
5,784 KB |
testcase_11 | AC | 3 ms
5,768 KB |
testcase_12 | AC | 4 ms
5,768 KB |
testcase_13 | AC | 7 ms
6,444 KB |
testcase_14 | AC | 199 ms
24,888 KB |
testcase_15 | AC | 196 ms
30,352 KB |
ソースコード
#include <bits/stdc++.h> using namespace std; class LCA { public: LCA(int n) : g(n), parent(21, vector<int>(n, -1)), depth(n) {} void add(int u, int v) { g[u].push_back(v); g[v].push_back(u); } void build() { dfs(0, -1); for (int i = 0; i < 20; i++) { for (int j = 0; j < g.size(); j++) { if (parent[i][j] != -1) { parent[i + 1][j] = parent[i][parent[i][j]]; } } } } int query(int u, int v) { if (depth[u] < depth[v]) swap(u, v); for (int i = 20; i >= 0; i--) { if (depth[u] - depth[v] >= 1 << i) { u = parent[i][u]; } } if (u == v) return u; for (int i = 20; i >= 0; i--) { if (parent[i][u] != parent[i][v]) { u = parent[i][u]; v = parent[i][v]; } } return parent[0][u]; } private: vector<vector<int>> g, parent; vector<int> depth; void dfs(int curr, int prev) { parent[0][curr] = prev; for (int next : g[curr]) if (next != prev) { depth[next] = depth[curr] + 1; dfs(next, curr); } } }; vector<int> g[101010]; long long cost[101010]; long long imos[101010]; void dfs(int curr, int prev) { for (int next : g[curr]) if (next != prev) { dfs(next, curr); } if (prev != -1) imos[prev] += imos[curr]; } int main() { int n; cin >> n; LCA lca(n); for (int i = 0; i < n - 1; i++) { int u, v; scanf("%d %d", &u, &v); g[u].push_back(v); g[v].push_back(u); lca.add(u, v); } lca.build(); for (int i = 0; i < n; i++) scanf("%lld", &cost[i]); long long ans = 0; int m; cin >> m; for (int i = 0; i < m; i++) { int a, b, c; scanf("%d %d %d", &a, &b, &c); int l = lca.query(a, b); ans += c * cost[l]; imos[a] += c; imos[b] += c; imos[l] -= 2 * c; } dfs(0, -1); for (int i = 0; i < n; i++) { ans += cost[i] * imos[i]; } cout << ans << endl; }