Submission #958055

#TimeUsernameProblemLanguageResultExecution timeMemory
958055MinaRagy06Beads and wires (APIO14_beads)C++17
0 / 100
4 ms11356 KiB
#include <bits/stdc++.h> using namespace std; #define ll long long const int N = 200'005; const ll inf = 1e18; ll dp[N][2][2]; vector<array<ll, 2>> adj[N]; void build(int i, int p) { vector<array<ll, 2>> newadj; for (auto [nxt, w] : adj[i]) { if (nxt == p) continue; build(nxt, i); newadj.push_back({nxt, w}); } adj[i] = newadj; } ll dfs(int i, int st, int carry) { if (~dp[i][st][carry]) { return dp[i][st][carry]; } ll ans = 0; if (carry) { ans = -inf; } if (!st) { for (auto [nxt, w] : adj[i]) { ans = max(ans, dfs(nxt, 0, 0)); } } ll s = 0; for (auto [nxt, w] : adj[i]) { s += max(dfs(nxt, 1, 1) + w, 0ll); } if (!carry) { ans = max(ans, s); } else { for (auto [nxt, w] : adj[i]) { ans = max(ans, s - max(dfs(nxt, 1, 1) + w, 0ll) + dfs(nxt, 1, 0) + w); } } ll mx[2] = {-inf, -inf}; for (auto [nxt, w] : adj[i]) { ll v = - max(dfs(nxt, 1, 1) + w, 0ll) + dfs(nxt, 1, 0) + w; if (v > mx[1]) { mx[1] = v; } if (mx[0] < mx[1]) swap(mx[0], mx[1]); } ans = max(ans, s + mx[0] + mx[1]); return dp[i][st][carry] = ans; } int main() { ios_base::sync_with_stdio(0), cin.tie(0); memset(dp, -1, sizeof dp); int n; cin >> n; for (int i = 1, u, v, w; i < n; i++) { cin >> u >> v >> w; adj[u].push_back({v, w}); adj[v].push_back({u, w}); } build(1, 0); cout << dfs(1, 0, 0) << '\n'; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...