Hdu 5834 Magic boy Bi Luo with his excited tree(从树上每个点
传送门:Hdu 5834 Magic boy Bi Luo with his excited tree
#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,w),addedge(v,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("%dn",max(up[i][0]+down[i][1],up[i][1]+down[i][0])); } return 0; } (编辑:威海站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |