Submission #520018

#TimeUsernameProblemLanguageResultExecution timeMemory
520018KoDPutovanje (COCI20_putovanje)C++17
110 / 110
110 ms22988 KiB
#include <bits/stdc++.h> using std::vector; using std::array; using std::pair; using std::tuple; template <class F> struct RecLambda : private F { explicit RecLambda(F&& f) : F(std::forward<F>(f)) {} template <class... Args> decltype(auto) operator()(Args&&... args) const { return F::operator()(*this, std::forward<Args>(args)...); } }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int N; std::cin >> N; vector<int> to(2 * N - 2), once(2 * N - 2), mult(2 * N - 2); vector<vector<int>> graph(N); for (int i = 0; i < N - 1; ++i) { int a, b, c, d; std::cin >> a >> b >> c >> d; a -= 1, b -= 1; to[2 * i] = b; to[2 * i + 1] = a; once[2 * i] = once[2 * i + 1] = c; mult[2 * i] = mult[2 * i + 1] = d; graph[a].push_back(2 * i); graph[b].push_back(2 * i + 1); } vector<int> depth(N); array<vector<int>, 20> parent; parent[0] = vector(N, 0); RecLambda([&](auto&& dfs, const int u, const int p) -> void { parent[0][u] = p; for (const int e : graph[u]) { if (to[e] != p) { depth[to[e]] = depth[u] + 1; dfs(to[e], u); } } })(0, 0); for (int k = 0; k < 19; ++k) { parent[k + 1] = vector(N, 0); for (int i = 0; i < N; ++i) { parent[k + 1][i] = parent[k][parent[k][i]]; } } const auto lca = [&](int u, int v) { if (depth[u] < depth[v]) { std::swap(u, v); } for (int dif = depth[u] - depth[v], k = 0; k < 20; ++k) { if (dif >> k & 1) { u = parent[k][u]; } } if (u == v) { return u; } for (int k = 19; k >= 0; --k) { if (parent[k][u] != parent[k][v]) { u = parent[k][u]; v = parent[k][v]; } } return parent[0][u]; }; vector<int> coeff(N); for (int i = 1; i < N; ++i) { const int j = lca(i - 1, i); coeff[i - 1] += 1; coeff[i] += 1; coeff[j] -= 2; } long long ans = 0; RecLambda([&](auto&& dfs, const int u, const int p) -> void { for (const int e : graph[u]) { if (to[e] != p) { dfs(to[e], u); coeff[u] += coeff[to[e]]; ans += std::min((long long)coeff[to[e]] * once[e], (long long)mult[e]); } } })(0, 0); std::cout << ans << '\n'; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...