This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#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));
// }
// }
for (int f = 0; f < 2; f++) {
ll s = 0;
for (auto [nxt, w] : adj[i]) {
s += max(dfs(nxt, 1, 1) + w, (carry || f? 0ll : dfs(nxt, 0, 0)));
}
if (!carry) {
ans = max(ans, s);
} else {
for (auto [nxt, w] : adj[i]) {
ans = max(ans, s - max(dfs(nxt, 1, 1) + w, (carry || f? 0ll : dfs(nxt, 0, 0))) + dfs(nxt, 1, 0) + w);
}
}
ll mx[2] = {-inf, -inf};
for (auto [nxt, w] : adj[i]) {
ll v = - max(dfs(nxt, 1, 1) + w, (carry || f? 0ll : dfs(nxt, 0, 0))) + dfs(nxt, 1, 0) + w;
if (v > mx[1]) {
mx[1] = v;
}
if (mx[0] < mx[1]) swap(mx[0], mx[1]);
}
if (!carry && f) {
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 time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |