[APIO2014]连珠线

CIII.[APIO2014]连珠线

一般的换根DP题。

明显可以看出,最终的树一定可以通过指定一个根变成一棵有根树,所有的蓝边都可以被分成两两一组,其中每组中两条边深度递增。

于是我们可以设置DP状态。\(f_{x,0/1}\)表示节点\(x\),它不是/是某对蓝边的中间节点时,子树中最大的蓝边权和。

简单使用multiset维护\(f_{x,1}\)从哪个儿子转移过来最优即可。

然后换个根即可。

代码:

#include<bits/stdc++.h>
using namespace std;
const int inf=0xc0c0c0c0;
int n,f[200100][2],head[200100],cnt,res;
struct node{
	int to,next,val;
}edge[400100];
void ae(int u,int v,int w){
	edge[cnt].next=head[u],edge[cnt].to=v,edge[cnt].val=w,head[u]=cnt++;
	edge[cnt].next=head[v],edge[cnt].to=u,edge[cnt].val=w,head[v]=cnt++;
}
multiset<int>s[200100];
void dfs1(int x,int fa){
	for(int i=head[x],y;i!=-1;i=edge[i].next){
		if((y=edge[i].to)==fa)continue;
		dfs1(y,x);
		int tmp=max(f[y][0],f[y][1]+edge[i].val);
		f[x][0]+=tmp;
		f[x][1]+=tmp,s[x].insert(f[y][0]+edge[i].val-tmp);
	}
	if(s[x].empty())f[x][1]=inf;
	else f[x][1]+=*s[x].rbegin();
//	printf("%d:%d %d\n",x,f[x][0],f[x][1]);
}
void dfs2(int x,int fa){
	for(int i=head[x],y;i!=-1;i=edge[i].next){
		if((y=edge[i].to)==fa)continue;
		int tmp=max(f[y][0],f[y][1]+edge[i].val);
		int fx0=f[x][0],fx1=f[x][1];
		fx0-=tmp;
		fx1-=tmp;
		fx1-=*s[x].rbegin();
		int pmt=f[y][0]+edge[i].val-tmp;
		s[x].erase(s[x].find(pmt));
		fx1=(s[x].empty()?inf:fx1+*s[x].rbegin());
		s[x].insert(pmt);
		
		int qwq=max(fx0,fx1+edge[i].val);
		f[y][0]+=qwq;
		f[y][1]=(s[y].empty()?0:f[y][1]-*s[y].rbegin());
		f[y][1]+=qwq;
		s[y].insert(fx0+edge[i].val-qwq);
		f[y][1]+=*s[y].rbegin();
		dfs2(y,x);
	}
}
int main(){
	scanf("%d",&n),memset(head,-1,sizeof(head));
	for(int i=1,x,y,z;i<n;i++)scanf("%d%d%d",&x,&y,&z),ae(x,y,z);
	dfs1(1,0),dfs2(1,0);
	for(int i=1;i<=n;i++)res=max(res,f[i][0]);
	printf("%d\n",res);
	return 0;
}

posted @ 2021-03-31 14:11  Troverld  阅读(54)  评论(0编辑  收藏  举报