Submission #1339390

#TimeUsernameProblemLanguageResultExecution timeMemory
1339390javkhlantogs구슬과 끈 (APIO14_beads)C++20
100 / 100
124 ms42512 KiB
#include<bits/stdc++.h>
#define ll long long
using namespace std;
vector<vector<pair<ll,ll>>> e;
vector<vector<ll>> dp;
vector<vector<pair<ll,ll>>> bestgain;
ll ans;
void dfs1(ll u,ll p){
	dp[u][0]=0;
	for(auto v:e[u]){
		if(v.first==p) continue;
		dfs1(v.first,u);
		dp[u][0]+=max(dp[v.first][1]+v.second,dp[v.first][0]);
		ll gain=dp[v.first][0]+v.second-max(dp[v.first][1]+v.second,dp[v.first][0]);
		bestgain[u].push_back({gain,v.first});
	}
	sort(bestgain[u].rbegin(),bestgain[u].rend());
	if(bestgain[u].size()>2) bestgain[u].resize(2);
	if(bestgain[u].size()==0) dp[u][1]=-1e18;
		else dp[u][1]=dp[u][0]+bestgain[u][0].first;
}
void dfs2(ll u,ll p,ll up0,ll up1,ll w){
	ll val=dp[u][0]+max(up0,up1+w);
	ans=max(ans,val);
	ll gp;
	if(u==1) gp=-1e18;
		else gp=(up0+w)-max(up0,up1+w);
	for(auto v:e[u]){
		if(v.first==p) continue;
		ll nextup0=val-max(dp[v.first][1]+v.second,dp[v.first][0]);	
		ll g=gp;
		if(bestgain[u].size()!=0 and bestgain[u][0].second!=v.first) g=max(g,bestgain[u][0].first);
			else if(bestgain[u].size()==2) g=max(g,bestgain[u][1].first);
		ll nextup1=nextup0+g;
		dfs2(v.first,u,nextup0,nextup1,v.second);
	}
}
int main(void){
	ios::sync_with_stdio(0); cin.tie(0);
	ll n,i,j,k,q;
	cin>>n;
	e.resize(n+1);
	bestgain.resize(n+1);
	dp.resize(n+1,vector<ll>(2));
	for(i=0 ; i<n-1 ; i++){
		cin>>j>>k>>q;
		e[j].push_back({k,q});
		e[k].push_back({j,q});
	}
	dfs1(1,1);
	ans=dp[1][0];
	dfs2(1,1,0,-1e18,0);
	cout<<ans<<"\n";
	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...