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 fi first
#define se second
using namespace std;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
const int N = 200005;
const int inf = numeric_limits<int>::max();
vpii t[N];
int n, a, b, w;
pii dp[N]; // first is without, second is with
void dfs(int v, int f, int val){
int sum = 0, mx0 = - inf, mx1 = - inf;
for(auto u : t[v])
if(u.fi != f){
dfs(u.fi, v, u.se);
int curr = max(dp[u.fi].fi, dp[u.fi].se);
sum += curr;
if(u.se - curr + dp[u.fi].fi > mx0)
mx1 = mx0, mx0 = u.se - curr + dp[u.fi].fi;
else if(u.se - curr + dp[u.fi].fi > mx1)
mx1 = u.se - curr + dp[u.fi].fi;
}
dp[v].fi = sum;
if(mx1 != - inf) dp[v].fi = max(mx1 + mx0, 0) + sum;
if(mx0 != - inf && f != - 1) dp[v].se = sum + mx0 + val;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for(int i = 0; i < n - 1; i++){
cin >> a >> b >> w;
t[a - 1].push_back({b - 1, w});
t[b - 1].push_back({a - 1, w});
}
dfs(0, - 1, 0);
cout << dp[0].fi << endl;
}
# | 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... |