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 all(fl) fl.begin(),fl.end()
#define pb push_back
#define fi first
#define se second
#define for1(i,j,k) for(int i=j;i<=k;i++)
#define for2(i,j,k) for(int i=j;i>=k;i--)
#define for3(i,j,k,l) for(int i=j;i<=k;i+=l)
#define lb lower_bound
#define ub upper_bound
#define sz(a) (int)a.size()
#define gcd __gcd
#define lcm(x,y) x*y/__gcd(x,y)
using pii=pair<int,int>;
using pli=pair<long long,int>;
const int maxn=2e5+9;
vector<pii>a[maxn];
int p[maxn];
const long long inf=-2e9-7;
long long dp[maxn][2];
long long f[maxn][2];
long long g[maxn][2];
void dfs1(int u,int par){
p[u]=par;
dp[u][1]=inf;
dp[u][0]=0;
for (auto v:a[u]){
if (v.fi==par)continue;
dfs1(v.fi,u);
dp[u][0]+=max(dp[v.fi][1]+v.se,dp[v.fi][0]);
}
long long choose=inf,notchoose=0;
for (auto v:a[u]){
if (v.fi==par)continue;
g[v.fi][0]=notchoose;
g[v.fi][1]=choose;
choose=max(choose+max(dp[v.fi][0],dp[v.fi][1]+v.se),notchoose+dp[v.fi][0]+v.se);
notchoose=notchoose+max(dp[v.fi][0],dp[v.fi][1]+v.se);
}
reverse(all(a[u]));
choose=inf,notchoose=0;
for (auto v:a[u]){
if (v.fi==par)continue;
g[v.fi][1]+=notchoose;
g[v.fi][0]+=choose;
choose=max(choose+max(dp[v.fi][0],dp[v.fi][1]+v.se),notchoose+dp[v.fi][0]+v.se);
notchoose=notchoose+max(dp[v.fi][0],dp[v.fi][1]+v.se);
}
reverse(all(a[u]));
dp[u][1]=choose;
}
signed main(){
srand(time(0));
ios_base::sync_with_stdio(0);
cin.tie(0);
//freopen(".INP","r",stdin);
//freopen(".OUT","w",stdout);
int n;
cin>>n;
for1(i,1,n-1){
int u,v,w;
cin>>u>>v>>w;
a[u].pb({v,w});
a[v].pb({u,w});
}
dfs1(1,0);
long long ans=dp[1][0];
for1(i,1,n){
for (auto v:a[i]){
if (v.fi==p[i]){
//dfs2(v.fi,i);
f[v.fi][0]=dp[v.fi][0]-max(dp[i][0],dp[i][1]+v.se);
f[v.fi][1]=max(g[i][0],g[i][1]);
}
}
long long value=0;
for (auto v:a[i]){
if (v.fi==p[i]){
value+=max(f[v.fi][0],f[v.fi][1]+v.se);
}
else {
value+=max(dp[v.fi][0],dp[v.fi][1]+v.se);
}
}
for1(j,0,sz(a[i])-1){
for1(k,j+1,sz(a[i])-1){
long long newvalue=value;
int v1=a[i][j].fi,v2=a[i][k].fi;
if (v1==p[i])newvalue-=max(f[v1][0],f[v1][1]+a[i][j].se)-f[v1][0];
else newvalue-=max(dp[v1][0],dp[v1][1]+a[i][j].se)-dp[v1][0];
if (v2==p[i])newvalue-=max(f[v2][0],f[v2][1]+a[i][k].se)-f[v2][0];
else newvalue-=max(dp[v2][0],dp[v2][1]+a[i][k].se)-dp[v2][0];
newvalue+=a[i][j].se+a[i][k].se;
ans=max(ans,newvalue);
}
}
}
cout<<ans;
}
# | 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... |