#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);
auto dfs = [&](auto &&self, int u, int p) -> void {
for (auto &[i, pr] : adj[u]) {
if (i == p) {
continue;
}
auto [c, d] = pr;
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 dfs2 = [&](auto &&self, int u,
int p) -> std::pair<long long, long long> {
long long up = 0;
long long pd = 0;
std::vector<long long> v;
for (auto &[i, pr] : adj[u]) {
if (i == p) {
continue;
}
auto [c, d] = pr;
up += d;
auto [del, _pd] = self(self, i, u);
up += del;
long long _v = std::max(_pd, path_down[i]);
pd = std::max(pd, pd);
v.push_back(_v);
}
ans = std::max(ans, up + pd - path_down[u]);
std::sort(v.rbegin(), v.rend());
if (v.size() > 1) {
ans = std::max(ans, up + v[0] + v[1] - path_down[u]);
}
return {up, pd};
};
dfs2(dfs2, 1, 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... |