#include <bits/stdc++.h>
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int n;
std::cin >> n;
std::vector<std::vector<std::pair<int, std::pair<long long, long long>>>> adj(
n + 1);
long long tot = 0;
for (int i = 0, a, b, c, d; i < n - 1; ++i) {
std::cin >> a >> b >> c >> d;
adj[a].push_back({b, {c, d}});
adj[b].push_back({a, {d, c}});
tot += c + d;
}
std::vector<long long> path_up(n + 1), path_down(n + 1);
long long up = 0;
auto dfs = [&](auto &&self, int u, int p) -> void {
for (auto &[i, pr] : adj[u]) {
if (i == p) {
continue;
}
auto [c, d] = pr;
up += d;
path_up[i] = path_up[u] + d;
path_down[i] = path_down[u] + c;
self(self, i, u);
}
};
dfs(dfs, 1, 0);
long long ans = 0;
auto dfs1 = [&](auto &&self, int u, int p, long long dep) -> long long {
// up + dep - path_up[u] ==> when rooted at u = [u]
// ans = max(ans, [u] + (max_down in the subtree of u - path_down[u]))
// then lca = cur node case ==> ans = max(ans, [u] + (v[0] - path_down[u]) +
// (v[1] - path_down[u]))
long long max_down = path_down[u];
std::vector<long long> v;
for (auto &[i, pr] : adj[u]) {
if (i == p) {
continue;
}
auto [c, d] = pr;
v.push_back(self(self, i, u, dep + c));
max_down = std::max(max_down, v.back());
}
long long _u_ = up + dep - path_up[u];
ans = std::max(ans, _u_ + (max_down - path_down[u]));
std::sort(v.rbegin(), v.rend());
if (v.size() > 1) {
ans = std::max(ans, _u_ + (v[0] - path_down[u]) + (v[1] - path_down[u]));
}
return max_down;
};
dfs1(dfs1, 1, 0, 0);
int q;
std::cin >> q;
while (q--) {
int x;
std::cout << tot - ans << '\n';
}
}
# | 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... |