Submission #494909

#TimeUsernameProblemLanguageResultExecution timeMemory
494909StickfishBeads and wires (APIO14_beads)C++17
100 / 100
188 ms22188 KiB
#include <iostream> #include <vector> using namespace std; const int MAXN = 2e5 + 123; const int INF = 1.77013e9; vector<pair<int, int>> edg[MAXN]; int dp0[MAXN]; int dp1[MAXN]; void update(int v, int rt) { dp0[v] = dp1[v] = 0; int rtw = -INF; for (auto [u, w] : edg[v]) { if (u == rt) { rtw = w; continue; } dp0[v] += max(dp0[u], dp1[u]); } dp1[v] = dp0[v]; if (rtw != -INF) { for (auto [u, w] : edg[v]) { if (u == rt) continue; dp1[v] = max(dp1[v], dp0[v] + rtw + w + min(0, dp0[u] - dp1[u])); } } } void get_ans(int v, int rt) { for (auto [u, w] : edg[v]) { if (u == rt) { continue; } get_ans(u, v); } update(v, rt); } int dfs(int v, int rt) { int dpv0 = dp0[v]; int dpv1 = dp1[v]; int ans = dp0[v]; int a0 = -INF; int a1 = -INF; for (auto [u, w] : edg[v]) { int x = w + min(0, dp0[u] - dp1[u]); if (x > a0) { a1 = a0; a0 = x; } else if (x > a1) { a1 = x; } } for (auto [u, w] : edg[v]) { if (u == rt) continue; int dpu0 = dp0[u]; int dpu1 = dp1[u]; dp0[v] -= max(dp0[u], dp1[u]); dp1[v] = dp0[v]; int x = w + min(0, dp0[u] - dp1[u]); if (x == a0) { if (a1 != -INF) dp1[v] = max(dp1[v], dp0[v] + w + a1); } else if (a0 != -INF) { dp1[v] = max(dp1[v], dp0[v] + w + a0); } update(u, -1); ans = max(ans, dfs(u, v)); dp0[v] = dpv0; dp1[v] = dpv1; dp0[u] = dpu0; dp1[u] = dpu1; } return ans; } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; for (int i = 0; i < n - 1; ++i) { int u, v, d; cin >> u >> v >> d; --u, --v; edg[u].push_back({v, d}); edg[v].push_back({u, d}); } get_ans(0, -1); int ans = dfs(0, -1); cout << ans << '\n'; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...