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;
const int Nmax = 2e5 + 5;
typedef long long ll;
const ll inf = 1e10;
ll dp[Nmax][4];
vector< pair<int,int> > v[Nmax];
void dfs(int node, int dad = 0)
{
vector<ll> zero, one, two;
int up = 0, son, i, cost;
for(auto it : v[node])
{
tie(son, cost) = it;
if(son != dad)
{
dfs(son, node);
zero.push_back(max(dp[son][0], dp[son][3]));
one.push_back(dp[son][1]);
two.push_back(dp[son][2]);
}
else up = cost;
}
/// case 0
ll sum = 0;
for(auto it : zero) sum += it;
dp[node][0] = max(dp[node][0], sum);
/// cases 1 & 2
ll best = sum, best1 = -inf, best2 = -inf;
for(i=0; i<zero.size(); ++i)
best = max(best, sum - zero[i] + one[i]);
for(i=0; i<zero.size(); ++i)
{
ll x = two[i] - zero[i];
if(x >= best1) best2 = best1, best1 = x;
else if(x > best2) best2 = x;
}
best = max(best, sum + best1 + best2);
best = max(-inf, best);
dp[node][1] = dp[node][2] = best;
/// case 3
best = -inf;
for(i=0; i<zero.size(); ++i)
best = max(best, sum - zero[i] + two[i]);
dp[node][3] = best;
///
dp[node][2] += up;
dp[node][3] += up;
}
int main()
{
// freopen("input", "r", stdin);
cin.sync_with_stdio(false);
int i, n, x, y, cost;
cin >> n;
for(i=1; i<=n; ++i) dp[i][0] = dp[i][1] = dp[i][2] = dp[i][3] = -inf;
for(i=1; i<n; ++i)
{
cin >> x >> y >> cost;
v[x].push_back({y, cost});
v[y].push_back({x, cost});
}
dfs(1);
cout << max(dp[1][0], dp[1][1]) << '\n';
return 0;
}
Compilation message (stderr)
beads.cpp: In function 'void dfs(int, int)':
beads.cpp:40:15: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for(i=0; i<zero.size(); ++i)
~^~~~~~~~~~~~
beads.cpp:43:15: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for(i=0; i<zero.size(); ++i)
~^~~~~~~~~~~~
beads.cpp:58:15: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for(i=0; i<zero.size(); ++i)
~^~~~~~~~~~~~
# | 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... |