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>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
ll n,dp[2][500005];
vector<pair<ll,ll> >v[500005];
void solve(ll x,ll par,ll dis){
ll mx1 = -99999999999 , mx2 = -99999999999 , sum = 0;
for(int i=0; i<v[x].size(); i++)
if(v[x][i].f != par){
ll to = v[x][i].f;
solve(to , x , v[x][i].s);
sum += max(dp[0][to] , dp[1][to]);
ll cur = dp[0][to] + v[x][i].s - max(dp[0][to] , dp[1][to]);
if(cur > mx1)mx2 = mx1 , mx1 = cur;
else if(cur > mx2)mx2 = cur;
}
dp[0][x] = sum;
if(v[x].size() - 1 + (x == 1) > 1)dp[0][x] = max(sum , sum + mx1 + mx2);
if(x != 1 && v[x].size() > 1)
dp[1][x] = sum + mx1 + dis;
//cout << x << " " << dp[0][x] << " " << dp[1][x] << '\n';
}
int main(){
ios::sync_with_stdio(false);
cin >> n;
for(int i=1; i<n; i++){
ll x,y,z;
cin >> x >> y >> z;
v[x].pb(mp(y , z));
v[y].pb(mp(x , z));
}
solve(1 , 0 , 0);
dp[0][1] = max(0LL , dp[0][1]);
cout << max(dp[0][1] , dp[1][1]) << '\n';
return 0;
}
Compilation message (stderr)
beads.cpp: In function 'void solve(long long int, long long int, long long int)':
beads.cpp:12:19: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for(int i=0; i<v[x].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... |