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>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define int long long
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define ppb pop_back
#define eb emplace_back
#define g0(a) get<0>(a)
#define g1(a) get<1>(a)
#define g2(a) get<2>(a)
#define g3(a) get<3>(a)
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
using db = double;
using ll = long long;
using ld = long double;
using ii = pair<int, int>;
using iii = tuple<int, int, int>;
using iiii = tuple<int, int, int, int>;
template<class key, class value = null_type, class cmp = less<key> >
using ordered_set = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>;
int n, mem[200005][2][2];
vector<ii> adj[200005];
int dp(int n, bool b, bool c, int e = -1) {
if (mem[n][b][c] != -1) return mem[n][b][c];
if (adj[n].size() - (e != -1) == 0) {
// leaf node
return b ? -(int)1e16 : 0;
}
int ret = -(int)1e16;
if (c) {
int case_1 = 0, case_2 = -(int)1e16;
vector<ii> reps;
for (auto [u, w] : adj[n]) if (u != e) {
int curr = max(dp(u, 0, 0, n), dp(u, 1, 0, n) + w);
case_1 += curr;
reps.eb(dp(u, 0, 1, n) + w - curr, u);
}
sort(reps.begin(), reps.end(), greater<ii>());
if (b) {
for (auto [u, w] : adj[n]) if (u != e) {
int curr = max(dp(u, 0, 0, n), dp(u, 1, 0, n) + w);
int m_val = -(int)1e16, s_val = -(int)1e16;
for (auto [v, idx] : reps) if (idx != u) {
if (v > s_val) s_val = v;
if (s_val > m_val) swap(m_val, s_val);
if (s_val != -(int)1e16) break;
}
int extra = max(0ll, m_val + s_val);
case_2 = max(case_2, extra + case_1 + dp(u, 0, 0, n) + w - curr);
}
case_1 = -(int)1e16;
} else {
if ((int)reps.size() >= 2) {
case_2 = case_1 + reps[0].first + reps[1].first;
}
}
ret = max({ret, case_1, case_2});
}
int rep = -(int)1e16, case_3 = 0;
for (auto [u, w] : adj[n]) if (u != e) {
int curr = max(dp(u, 0, c, n), dp(u, 1, c, n) + w);
case_3 += curr;
rep = max(rep, dp(u, 0, c, n) + w - curr);
}
if (b) case_3 += rep;
ret = max(ret, case_3);
return mem[n][b][c] = ret;
}
main() {
memset(mem, -1, sizeof mem);
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 1, u, v, w; i < n; i++) {
cin >> u >> v >> w;
adj[u].eb(v, w);
adj[v].eb(u, w);
}
cout << dp(1, 0, 1) << '\n';
}
Compilation message (stderr)
beads.cpp:76:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
76 | main() {
| ^~~~
# | 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... |