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
using pii = pair<int, int>;
const int N = 2e5 + 10;
int n;
vector<pii> ad[N];
int f[N][2];
void dfs(int u, int pre = 0) {
int sacrifice = -1e9, none = -1e9;
vector<pii> best;
best.push_back({-1, 0});
best.push_back({-1, 0});
for (auto duck : ad[u]) {
int v, w; tie(v, w) = duck;
if (v == pre) continue;
dfs(v, u);
sacrifice = max(0ll, sacrifice);
if (f[v][1] > 0) {
sacrifice += f[v][1] + w;
none = max(none, f[v][0] - f[v][1]);
} else none = max(none, f[v][0] + w);
best.push_back({v, w});
}
f[u][1] = max({sacrifice, sacrifice + none, -1ll});
sort(best.begin(), best.end(), [&](pii a, pii b) {
int x = a.first, y = b.first;
if (x == -1) return false;
if (y == -1) return true;
return make_pair(f[x][0] - f[x][1], a.second) > make_pair(f[y][0] - f[y][1], b.second);
});
pii a, b; a = best[0], b = best[1];
if (b.first > 0) f[u][0] = f[a.first][0] + f[b.first][0] + a.second + b.second;
int zeoh = 0;
for (auto duck : ad[u]) {
int v, w; tie(v, w) = duck;
if (v == pre) continue;
if (v != a.first && v != b.first && f[v][1] > 0) f[u][0] += f[v][1] + w;
if (f[v][1] > 0) zeoh += f[v][1] + w;
}
f[u][0] = max(f[u][0], zeoh);
}
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);
}
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});
}
dfs(1);
cout << f[1][0];
}
Compilation message (stderr)
beads.cpp: In function 'int32_t main()':
beads.cpp:69:12: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
69 | freopen("duck.inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
beads.cpp:70:12: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
70 | 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... |