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 N 200000
vector<pair<unsigned, int>> g[N];
int dp1[N], dp2[N]; // Use or don't use the parent edge.
void calc_dp(unsigned u, unsigned parent, int parent_edge_w)
{
int diff_max1 = INT_MIN, diff_max2 = INT_MIN;
for (auto const &[v, w] : g[u])
{
if (v != parent)
{
calc_dp(v, u, w);
dp1[u] += dp1[v];
dp2[u] += dp1[v];
if (dp2[v] + w - dp1[v] > diff_max1)
{
diff_max2 = diff_max1;
diff_max1 = dp2[v] + w - dp1[v];
}
else if (dp2[v] + w - dp1[v] > diff_max2)
{
diff_max2 = dp2[v] + w - dp1[v];
}
}
}
if (diff_max1 != INT_MIN)
dp1[u] += parent_edge_w + diff_max1;
if (diff_max2 != INT_MIN)
dp2[u] += diff_max1 + diff_max2;
}
int main()
{
size_t n;
scanf("%zu", &n);
for (size_t i = 0; i < n - 1; i++)
{
unsigned u, v, w;
cin >> u >> v >> w;
g[u - 1].emplace_back(v - 1, w);
g[v - 1].emplace_back(u - 1, w);
}
calc_dp(0, -1, 0);
printf("%d\n", dp2[0]);
}
Compilation message (stderr)
beads.cpp: In function 'int main()':
beads.cpp:41:10: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
41 | scanf("%zu", &n);
| ~~~~~^~~~~~~~~~~
# | 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... |