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;
#define int long long
const int N=2e5+10, inf=1e18;
int f[N][2][3][3];
vector<pair<int, int>> g[N];
void dfs(int u, int p){
int wpar=0;
for (int i=0; i<(int)g[u].size(); ++i) if (g[u][i].first==p){
wpar=g[u][i].second;
g[u].erase(g[u].begin()+i);
break;
}
for (auto &e:g[u]) dfs(e.first, u);
vector<int> sum(3);
for (auto &e:g[u]){
int v=e.first;
for (int i=0; i<3; ++i) sum[i]+=max(f[v][0][i][0], f[v][1][i][1]);
}
f[u][0][0][0]=sum[0];
if ((int)g[u].size()>=2){
vector<vector<pair<int, int>>> diff(3);
for (auto &e:g[u]){
int v=e.first, w=e.second;
for (int i=0; i<3; ++i) diff[i].emplace_back(f[v][0][1][i]+w-max(f[v][0][1][0], f[v][1][1][1]), v);
}
for (int i=0; i<3; ++i) sort(diff[i].rbegin(), diff[i].rend());
int mxdiff=-inf;
for (int c2=0; c2<3; ++c2){
int c1=0;
for (int i1=0; i1<2; ++i1) for (int i2=0; i2<2; ++i2) if (diff[c1][i1].second!=diff[c2][i2].second){
mxdiff=max(mxdiff, diff[c1][i1].first+diff[c2][i2].first);
}
}
f[u][0][0][1]=sum[1]+mxdiff;
}
if (g[u].size()){
vector<int> diff;
for (auto &e:g[u]){
int v=e.first;
diff.push_back(max({f[v][0][2][1], f[v][0][2][2], f[v][1][2][1]})-max(f[v][0][2][0], f[v][1][2][1]));
}
sort(diff.rbegin(), diff.rend());
f[u][0][0][2]=sum[2]+diff[0];
}
if (p && g[u].size()){
vector<int> diff;
for (auto &e:g[u]){
int v=e.first, w=e.second;
diff.push_back(f[v][0][1][0]+w+wpar-max(f[v][0][1][0], f[v][1][1][1]));
}
sort(diff.rbegin(), diff.rend());
f[u][1][0][1]=sum[1]+diff[0];
}
if (p && g[u].size()){
vector<int> diff;
for (auto &e:g[u]){
int v=e.first, w=e.second;
diff.push_back(max(f[v][0][1][1], f[v][0][1][2])+w+wpar-max(f[v][0][1][0], f[v][1][1][1]));
}
sort(diff.rbegin(), diff.rend());
f[u][1][2][1]=sum[1]+diff[0];
}
for (int i=0; i<2; ++i) for (int j=0; j<3; ++j){
f[u][i][1][j]=max(f[u][i][1][j], f[u][i][0][j]);
f[u][i][2][j]=max(f[u][i][2][j], f[u][i][0][j]);
}
}
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 << max({f[1][0][0][0], f[1][0][0][1], f[1][0][0][2]});
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... |