传送门:Hdu 5834 Magic boy Bi Luo with his excited tree
题意:给你一棵树,有n个点,每个点都有一个利润,每条边都有一个花费,问从每个点出发,获得的最大的利润为多少(每个点上的利润只能取一次,每条边每走一次就要花费)
思路:我们任意选取一个根,每个点都保存四个值,down[i][0],down[i][1]分别表示向下不回到这个点和回到这个点所能获取的最大利润
up[i][0]和up[i][1]分别表示向上回到这个点和不回到这个点所能获取的利润的最大值down[i][1]是能容易计算的,down[i][0]可以通过这样去计算,它是由若干条回到i这个点的和一条不会来的路径组成
先把这个点u的子节点v中down[v][1]-e(u,v)*2大于等于0的直接加上来,并把这些点进行标记,那么我们再找寻一条不回来的路径就可以了定义up[i]不包括i这个点
up[i][1]也是很容易计算,up[i][0]的计算也可以分为两类
1.父亲结点向上返回+父亲结点向下不返回
2.父亲结点向上不返回+父亲结点向下返回
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+7;
struct Edge{
int to,next,cost;
}e[maxn*2];
int head[maxn],tot;
int down[maxn][2],ans[maxn],up[maxn][2],vis[maxn],val[maxn];
void init(){
tot=0;
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
}
void addedge(int from,int to,int cost){
e[tot]=(Edge){to,head[from],cost};
head[from]=tot++;
}
void dfs1(int u,int pre){
down[u][0]=down[u][1]=val[u];
int maxv=0,another_maxv=0;
for(int i=head[u];i!=-1;i=e[i].next){
int v=e[i].to;
if(v==pre) continue;
dfs1(v,u);
if(down[v][1]-2*e[i].cost>=0)
maxv+=down[v][1]-2*e[i].cost,down[u][1]+=down[v][1]-2*e[i].cost;
}
for(int i=head[u];i!=-1;i=e[i].next){
int v=e[i].to;
if(v==pre) continue;
if(down[v][1]-2*e[i].cost>=0){
if(another_maxv<maxv+down[v][0]-e[i].cost-(down[v][1]-2*e[i].cost))
another_maxv=maxv+down[v][0]-e[i].cost-(down[v][1]-2*e[i].cost),vis[u]=v;
}
else
if(another_maxv<maxv+down[v][0]-e[i].cost)
another_maxv=maxv+down[v][0]-e[i].cost,vis[u]=v;
}
down[u][0]+=another_maxv;
}
void dfs2(int u,int pre){
for(int i=head[u];i!=-1;i=e[i].next){
int v=e[i].to;
if(v==pre) continue;
//计算向上返回
int tmp=up[u][1]+down[u][1];
if(down[v][1]-2*e[i].cost>=0)
up[v][1]=max(0,tmp-2*e[i].cost- (down[v][1]-2*e[i].cost) );
else
up[v][1]=max(0,tmp-2*e[i].cost);
//计算向上不返回
//第一种情况,u向上不返回+u向下返回
tmp=up[u][0]+down[u][1];
if(down[v][1]-2*e[i].cost>=0)
tmp-=(down[v][1]-2*e[i].cost);
tmp=max(tmp-e[i].cost,0);
//第二种情况,向上返回+向下不返回
int tmp1=up[u][1];
if(vis[u]==v){ //重新计算
int maxv=0,another_maxv=0;
for(int j=head[u];j!=-1;j=e[j].next){
int V=e[j].to;
if(V==pre||V==v)
continue;
if(down[V][1]-2*e[j].cost>=0)
maxv+=down[V][1]-2*e[j].cost;
}
for(int j=head[u];j!=-1;j=e[j].next){
int V=e[j].to;
if(V==pre||V==v) continue;
if(down[V][1]-2*e[j].cost>=0)
another_maxv=max(another_maxv,maxv+down[V][0]-e[j].cost-(down[V][1]-2*e[j].cost));
else
another_maxv=max(another_maxv,maxv+down[V][0]-e[j].cost);
}
tmp1+=val[u]+another_maxv;
}
else{
tmp1+=down[u][0];
if(down[v][1]-2*e[i].cost>=0)
tmp1-=(down[v][1]-2*e[i].cost);
}
tmp1=max(tmp1-e[i].cost,0);
up[v][0]=max(tmp1,tmp);
dfs2(v,u);
}
}
int main(){
int _,n,u,v,w;
scanf("%d",&_);
for(int case1=1;case1<=_;case1++){
init();
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&val[i]);
for(int i=1;i<n;i++)
scanf("%d%d%d",&u,&v,&w),addedge(u,v,w),addedge(v,u,w);
up[1][0]=up[1][1]=0;
dfs1(1,0);
dfs2(1,0);
printf("Case #%d:\n",case1);
for(int i=1;i<=n;i++)
printf("%d\n",max(up[i][0]+down[i][1],up[i][1]+down[i][0]));
}
return 0;
}