This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#ifdef __LOCAL__
#include <debug_local.h>
#endif
using namespace std;
const int mxN = 1e5 + 5;
const int lg = 18;
vector<int> ad[mxN];
vector<tuple<int, int, int>> ll[mxN];
int par[mxN][lg];
int depth[mxN];
int dp[mxN];
int in[mxN], out[mxN];
int timer;
int t[4 * mxN];
int n;
void update(int x, int lx, int rx, int l, int r, int v) {
if (l > rx || lx > r) return;
if (l <= lx && r >= rx) {
t[x] += v;
return;
}
int mx = (lx + rx) >> 1;
update(x << 1, lx, mx, l, r, v);
update(x << 1 | 1, mx + 1, rx, l, r, v);
}
void update(int u, int v) {
update(1, 1, n, in[u], out[u], v);
}
int query(int x, int lx, int rx, int i) {
if (lx == rx) return t[x];
int mx = (lx + rx) >> 1;
if (i <= mx) return t[x] + query(x << 1, lx, mx, i);
return t[x] + query(x << 1 | 1, mx + 1, rx, i);
}
int query(int u) {
return query(1, 1, n, in[u]);
}
void dfs(int u, int p) {
in[u] = ++timer;
par[u][0] = p;
depth[u] = depth[p] + 1;
for (int i = 1; i < lg; i++) par[u][i] = par[par[u][i - 1]][i - 1];
for (int v : ad[u]) {
if (v == p) continue;
dfs(v, u);
}
out[u] = timer;
}
int __lca(int u, int v) {
if (depth[u] > depth[v]) swap(u, v);
for (int j = lg - 1; j >= 0; j--) {
if (depth[par[v][j]] >= depth[u]) v = par[v][j];
}
if (u == v) return u;
for (int j = lg - 1; j >= 0; j--) {
if (par[v][j] != par[u][j]) u = par[u][j], v = par[v][j];
}
return par[v][0];
}
void dfs1(int u, int p) {
dp[u] = 0;
int s = 0;
for (int v : ad[u]) {
if (v == p) continue;
dfs1(v, u);
s += dp[v];
}
dp[u] = s;
for (auto [a, b, c] : ll[u]) {
dp[u] = max(dp[u], s + query(a) + query(b) + c);
}
update(u, s - dp[u]);
}
void testCase() {
cin >> n;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
ad[u].push_back(v);
ad[v].push_back(u);
}
dfs(1, 0);
int m;
cin >> m;
while (m--) {
int u, v, c;
cin >> u >> v >> c;
int lca = __lca(u, v);
ll[lca].push_back({u, v, c});
}
dfs1(1, 0);
cout << dp[1] << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
testCase();
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |