Submission #916296

#TimeUsernameProblemLanguageResultExecution timeMemory
916296AlcabelBeads and wires (APIO14_beads)C++17
100 / 100
154 ms26308 KiB
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5; const long long inf = 1e13; vector<pair<int, int>> g[maxn]; long long dp[maxn][2]; void dfsCalc(int v, int p) { dp[v][0] = 0, dp[v][1] = -inf; for (const auto& [u, w] : g[v]) { if (u != p) { dfsCalc(u, v); dp[v][0] += max(dp[u][0], dp[u][1] + w); } } for (const auto& [u, w] : g[v]) { if (u != p) { dp[v][1] = max(dp[v][1], dp[v][0] - max(dp[u][0], dp[u][1] + w) + dp[u][0] + w); } } } long long up[maxn][2]; long long dfsAns(int v, int p, int pw) { long long ans, whole; ans = whole = dp[v][0] + max(up[v][0], up[v][1] + pw); pair<long long, int> max1 = {-inf, -2}, max2 = {-inf, -2}, cur; if (p != -1) { cur = {-max(up[v][0], up[v][1] + pw) + up[v][0] + pw, -1}; if (cur >= max1) { max2 = max1, max1 = cur; } else if (cur > max2) { max2 = cur; } } for (const auto& [u, w] : g[v]) { if (u != p) { cur = {-max(dp[u][0], dp[u][1] + w) + dp[u][0] + w, u}; if (cur >= max1) { max2 = max1, max1 = cur; } else if (cur > max2) { max2 = cur; } } } for (const auto& [u, w] : g[v]) { if (u != p) { up[u][0] = whole - max(dp[u][0], dp[u][1] + w); if (max1.second != u) { up[u][1] = up[u][0] + max1.first; } else { up[u][1] = up[u][0] + max2.first; } ans = max(ans, dfsAns(u, v, w)); } } return ans; } void solve() { int n; cin >> n; for (int i = 0; i < n - 1; ++i) { int v, u, w; cin >> v >> u >> w; --v, --u; g[v].emplace_back(u, w); g[u].emplace_back(v, w); } dfsCalc(0, -1); up[0][0] = up[0][1] = 0; cout << dfsAns(0, -1, 0) << '\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifdef LOCAL freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int T = 1; cin >> T; while (T--) { solve(); cerr << "-----------\n"; cout << "-----------\n"; } #else int T = 1; // cin >> T; while (T--) { solve(); } #endif 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...