This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// from duckindog wth depression
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2e5 + 10;
int n;
vector<pair<int, int>> ad[N];
int f[2][N];
int pa[N];
void init_dfs(int u, int pre = 0) {
int all = -1e15, none = -1e15;
for (auto duck : ad[u]) {
int v, w; tie(v, w) = duck;
if (v == pre) continue;
if (all == -1e15) all = 0;
pa[v] = w;
init_dfs(v, u);
int best = max(f[1][v] + w, f[0][v]);
all += best;
none = max(none, f[0][v] + w - best);
}
f[0][u] = max(0ll, all);
f[1][u] = all + none;
}
using pii = pair<int, int>;
int g[2][N];
void dfs(int u, int pre = 0) {
vector<pii> best;
int all = 0;
for (auto duck : ad[u]) {
int v, w; tie(v, w) = duck;
if (v == pre) continue;
best.push_back({v, w});
all += max(f[1][v] + w, f[0][v]);
}
best.push_back({n + 1, -1e8});
best.push_back({n + 1, -1e8});
sort(best.begin(), best.end(), [&] (pii a, pii b) {
int i, j; tie(i, j) = a;
int t, l; tie(t, l) = b;
return f[0][i] + j - max(f[0][i], f[1][i] + j) > f[0][t] + l - max(f[0][t], f[1][t] + l);
});
pii fi = best[0], se = best[1];
for (auto duck : ad[u]) {
int v, w; tie(v, w) = duck;
if (v == pre) continue;
int a, b; tie(a, b) = (v == fi.first ? se : fi);
int sum = all - max(f[1][v] + w, f[0][v]);
g[0][v] = max(g[0][v], sum - max(f[0][a], f[1][a] + b) + f[0][a] + b + g[0][u] + w);
g[0][v] = max(g[0][v], max(g[0][u], g[1][u] + w) + sum);
g[0][v] = max(g[0][v], f[0][u] - max(f[1][v] + w, f[0][v]));
g[1][v] = f[0][u] - max(f[1][v] + w, f[0][v]) + g[0][u] + w;
dfs(v, u);
}
}
int32_t main() {
cin.tie(0)->sync_with_stdio(0);
if (fopen("duck.inp", "r")) {
freopen("duck.inp", "r", stdin);
freopen("duck.out", "w", stdout);
}
g[n + 1][0] = g[n + 1][1] = -1e8;
cin >> n;
for (int i = 1; i < n; ++i) {
int u, v, w; cin >> u >> v >> w;
ad[u].push_back({v, w});
ad[v].push_back({u, w});
}
init_dfs(1);
dfs(1);
int answer = 0;
for (int i = 1; i <= n; ++i) answer = max(answer, f[0][i] + g[0][i]);
cout << answer;
}
Compilation message (stderr)
beads.cpp: In function 'int32_t main()':
beads.cpp:87:12: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
87 | freopen("duck.inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
beads.cpp:88:12: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
88 | freopen("duck.out", "w", stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
# | 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... |