Submission #363143

#TimeUsernameProblemLanguageResultExecution timeMemory
363143shivensinha4Beads and wires (APIO14_beads)C++17
100 / 100
228 ms18016 KiB
#include "bits/stdc++.h" using namespace std; #define for_(i, s, e) for (int i = s; i < (int) e; i++) #define for__(i, s, e) for (ll i = s; i < e; i++) typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; //#define endl '\n' const int MXN = 2e5, INF = 1e9; vector<array<int, 2>> dp; vector<vector<array<int, 2>>> adj; int n, ans = 0; void dfs(int p, int parent, int pe=0) { dp[p] = {0, 0}; int v = 0; for (auto i: adj[p]) if (i[0] != parent) { dfs(i[0], p, i[1]); v = max(v, -dp[i[0]][0] + dp[i[0]][1] + i[1] + pe); dp[p][1] += dp[i[0]][0]; } dp[p][0] = dp[p][1] + (p == parent ? 0 : v); } void reroot(int p, int parent) { array<int, 2> opt = {-INF, -INF}, pre = dp[p]; if (parent != p) dp[p][1] += dp[parent][0]; for (auto i: adj[p]) { int temp = -dp[i[0]][0] + dp[i[0]][1] + i[1]; if (temp >= opt[0]) { swap(opt[0], opt[1]); opt[0] = temp; } else if (temp > opt[1]) opt[1] = temp; } ans = max(ans, dp[p][1]); for (auto i: adj[p]) if (i[0] != parent) { dp[p][1] -= dp[i[0]][0]; dp[p][0] = dp[p][1]; int temp = -dp[i[0]][0] + dp[i[0]][1] + i[1]; if (temp == opt[0]) dp[p][0] += max(opt[1]+i[1], 0); else dp[p][0] += max(opt[0]+i[1], 0); reroot(i[0], p); dp[p][1] += dp[i[0]][0]; } dp[p] = pre; } int main() { #ifdef mlocal freopen("test.in", "r", stdin); #endif ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; dp.resize(n); adj.resize(n); for_(i, 0, n-1) { int a, b, w; cin >> a >> b >> w; a -= 1; b -= 1; adj[a].push_back({b, w}); adj[b].push_back({a, w}); } dfs(0, 0, 0); reroot(0, 0); cout << ans << endl; 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...