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>> tadj[N], adj[N];
void build(int i, int p) {
adj[i].clear();
for (auto [nxt, w] : tadj[i]) {
if (nxt == p) continue;
build(nxt, i);
adj[i].push_back({nxt, w});
}
}
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;
}
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]);
// }
}
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;
tadj[u].push_back({v, w});
tadj[v].push_back({u, w});
}
ll ans = 0;
for (int i = 1; i <= n; i++) {
build(i, 0);
ans = max(ans, dfs(i, 0, 0));
}
cout << ans << '\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... |