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<iostream>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
#include<tuple>
#include<set>
#include<map>
#include<random>
#include<chrono>
using namespace std;
const int MAX_N=2e5+1;
const int INF=2e9+1e8;
int dpdown[MAX_N][2];
int dpup[MAX_N][2];
int best[MAX_N];
int best2[MAX_N];
int sum[MAX_N];
int n;
vector<pair<int,int>>g[MAX_N];
void dfsdown(int u,int par)
{
vector<int>ch;
for(auto [v,edge]:g[u])
{
if(v==par)continue;
dfsdown(v,u);
sum[u]+=max(edge+dpdown[v][1],dpdown[v][0]);
ch.push_back(-max(edge+dpdown[v][1],dpdown[v][0])+edge+dpdown[v][0]);
}
sort(ch.rbegin(),ch.rend());
if(ch.size())
{
dpdown[u][1]=sum[u]+ch[0];
best[u]=ch[0];
}
else dpdown[u][1]=-INF;
if(ch.size()>1)best2[u]=ch[1];
dpdown[u][0]=sum[u];
}
void dfsup(int u,int par)
{
for(auto [v,edge]:g[u])
{
if(v==par)continue;
int cur1=max(edge+dpdown[v][1],dpdown[v][0]);
int cur2=-cur1+edge+dpdown[v][0];
dpup[v][1]=sum[u]-cur1+edge+dpup[u][0];
dpup[v][0]=max(sum[u]+(cur2==best[u] ? best2[u] : best[u])-cur1+dpup[u][0]+edge,//put blue in subtree
sum[u]-cur1+dpup[u][1]+edge); //put blue up
dpup[v][0]=max(dpup[v][0],sum[u]-cur1+dpup[u][0]);//put red
dfsup(v,u);
}
}
signed main ()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
cin>>n;
for(int i=1;i<n;i++)
{
int u,v,c;
cin>>u>>v>>c;
g[u].push_back({v,c});
g[v].push_back({u,c});
}
dfsdown(1,0);
dfsup(1,0);
int ans=0;
for(int i=1;i<=n;i++)
{
ans=max(ans,dpdown[i][0]+dpup[i][0]);
}
cout<<ans<<"\n";
return 0;
}
Compilation message (stderr)
beads.cpp: In function 'void dfsdown(int, int)':
beads.cpp:27:14: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
27 | for(auto [v,edge]:g[u])
| ^
beads.cpp: In function 'void dfsup(int, int)':
beads.cpp:51:14: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
51 | for(auto [v,edge]:g[u])
| ^
# | 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... |