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 N=2e5+10;
int f[N][2];
vector<pair<int, int>> g[N];
void dfs(int u, int p){
for (auto &e:g[u]) if (e.first!=p) dfs(e.first, u);
vector<int> vv;
for (auto &e:g[u]){
int v=e.first, w=e.second;
if (v==p) continue;
f[u][0]+=max(f[v][0], f[v][1]), vv.push_back(f[v][0]+w-max(f[v][0], f[v][1]));
}
if ((int)vv.size()>=2){
int m1=vv[0], m2=vv[1];
if (m1<m2) swap(m1, m2);
for (int i=2; i<(int)vv.size(); ++i){
if (m1<vv[i]) m2=m1, m1=vv[i];
else m2=max(m2, vv[i]);
}
f[u][0]=max(f[u][0], f[u][0]+m1+m2);
}
if (p && (int)g[u].size()>1){
int wpar=0;
for (auto &e:g[p]) if (e.first==u) wpar=e.second;
int m=INT_MIN;
for (auto &e:g[u]){
int v=e.first, w=e.second;
if (v==p) continue;
f[u][1]+=max(f[v][0], f[v][1]);
m=max(m, f[v][0]+w-max(f[v][0], f[v][1])+wpar);
}
f[u][1]+=m;
}
}
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int i=1; i<n; ++i){
int u, v, w; cin >> u >> v >> w;
g[u].emplace_back(v, w);
g[v].emplace_back(u, w);
}
dfs(1, 0);
cout << f[1][0];
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... |