#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=200010, INF=1e15;
int n, pw[N], dp[2][N], ep[N];
vector<pair<int, int>> adj[N];
void dfs(int curr, int prev) {
int sum=0, mx=-INF, mx1=-INF, mx2=-INF, mx3=-INF;
vector<int> vec;
for(auto [next, w]:adj[curr]) if(next!=prev) {
pw[next]=w, dfs(next, curr);
dp[0][curr]+=max({dp[0][next], dp[1][next], ep[next]});
sum+=max(dp[0][next], ep[next]);
if(max(dp[0][next], dp[1][next])>=ep[next]) mx=max(mx, w);
else mx=max(mx, max(dp[0][next], dp[1][next])+w-ep[next]);
if(dp[0][next]>=ep[next]) {
if(mx1<w) mx2=mx1, mx1=w;
else if(mx2<w) mx2=w;
}
else {
if(mx1<dp[0][next]+w-ep[next]) mx2=mx1, mx1=dp[0][next]+w-ep[next];
else if(mx2<dp[0][next]+w-ep[next]) mx2=dp[0][next]+w-ep[next];
}
vec.push_back(mx1);
}
dp[1][curr]=sum+mx1+mx2;
reverse(adj[curr].begin(), adj[curr].end());
int p=(int)vec.size()-1;
for(auto [next, w]:adj[curr]) if(next!=prev) {
dp[1][curr]=max(dp[1][curr], sum-max(dp[0][next], ep[next])+dp[1][next]+max(mx3, p?vec[--p]:-INF));
if(dp[0][next]>=ep[next]) mx3=max(mx3, w);
else mx3=max(mx3, dp[0][next]+w-ep[next]);
}
ep[curr]=dp[0][curr]+mx+pw[curr];
}
signed main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>n;
for(int i=1; i<n; i++) {
int u, v, w; cin>>u>>v>>w;
adj[u].push_back({v, w}), adj[v].push_back({u, w});
}
fill(dp[1]+1, dp[1]+n+1, -INF), fill(ep+1, ep+n+1, -INF);
dfs(1, 0);
cout<<max(dp[0][1], dp[1][1]);
return 0;
}
# | 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... |