Submission #971248

#TimeUsernameProblemLanguageResultExecution timeMemory
971248kilkuwuBeads and wires (APIO14_beads)C++17
100 / 100
135 ms24892 KiB
#include <bits/stdc++.h> #define nl '\n' #ifdef LOCAL #include "template/debug.hpp" #else #define dbg(...) ; #define timer(...) ; #endif const int mxN = 2e5 + 5; int dp[mxN][2][2], up[mxN]; std::vector<std::pair<int, int>> adj[mxN]; int N; int dfs(int u, int p, int e, int b) { if (dp[u][e][b] != -1) return dp[u][e][b]; std::vector<int> child; for (auto [v, c] : adj[u]) { if (v == p) continue; up[v] = c; child.push_back(v); dfs(v, u, 0, 0); dfs(v, u, 0, 1); dfs(v, u, 1, 0); dfs(v, u, 1, 1); } int& ans = dp[u][e][b]; int sum_e_no_b = 0; for (int v : child) { sum_e_no_b += dp[v][1][0]; } ans = sum_e_no_b; if (b) { for (int v : child) { ans = std::max(ans, sum_e_no_b - dp[v][1][0] + dp[v][1][1]); } if (child.size() >= 2) { std::sort(child.begin(), child.end(), [&](int i, int j) { return dp[i][0][0] + up[i] - dp[i][1][0] > dp[j][0][0] + up[j] - dp[j][1][0]; }); for (int v : child) { int cand = sum_e_no_b - dp[v][1][0] + dp[v][0][1] + up[v]; int vv = child[0] == v ? child[1] : child[0]; cand += dp[vv][0][0] + up[vv] - dp[vv][1][0]; ans = std::max(ans, cand); } } } if (e) { for (int v : child) { int cand = sum_e_no_b + up[u] + up[v] + dp[v][0][b] - dp[v][1][0]; ans = std::max(ans, cand); } } return ans; } signed main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); memset(dp, -1, sizeof(dp)); std::cin >> N; for (int i = 0; i + 1 < N; i++) { int u, v, c; std::cin >> u >> v >> c; --u, --v; adj[u].emplace_back(v, c); adj[v].emplace_back(u, c); } std::cout << dfs(0, 0, 0, 1) << nl; } /* 10 4 10 2 1 2 21 1 3 13 6 7 1 7 9 5 2 4 3 2 5 8 1 6 55 6 8 34 */
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...