1. 程式人生 > 實用技巧 >hdu_5834 Magic boy Bi Luo with his excited tree

hdu_5834 Magic boy Bi Luo with his excited tree

#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm> 
using namespace std;
int T,n,val[100010],c_back[100010],c[100010],ans[100010],choose[100010];
struct edge{int v,w;};
vector<edge> G[100010];

void dfs(int u,int fa){
    for(int i=0;i<G[u].size();i++){
        int v=G[u][i].v,w=G[u][i].w;
        if(v==fa)continue;
        dfs(v,u);
        if(c_back[v]-w*2+val[v]>0)c_back[u]+=c_back[v]-w*2+val[v];
    }
    c[u]=c_back[u]; 
    for(int i=0;i<G[u].size();i++){
        int v=G[u][i].v,w=G[u][i].w;
        if(v==fa)continue;
        if(c_back[v]-w*2+val[v]>0){
        	if(c_back[u]-c_back[v]+w+c[v]>c[u])choose[u]=v;
			c[u]=max(c[u],c_back[u]-c_back[v]+w+c[v]);
		}
        else {
        	if(c_back[u]+c[v]+val[v]-w>c[u])choose[u]=v;
			c[u]=max(c[u],c_back[u]+c[v]+val[v]-w);
		}
    }
}

void dfs2(int u,int fa,int last){
    int re,re_c,re_=c_back[u],re_c_=c[u],rechoose,rechoose_=choose[u];
    if(fa!=-1){
    	re_c=c[fa],re=c_back[fa],rechoose=choose[fa];
        if(c_back[u]-2*last>0)c_back[fa]-=(c_back[u]-2*last);
        if(c_back[fa]-2*last>0)c_back[u]+=(c_back[fa]-2*last);
        if(choose[fa]!=u && re_-2*last>0)c[fa]-=(re_-2*last);
        else {
			c[fa]=c_back[fa];
			for(int i=0;i<G[fa].size();i++){
	            int v=G[fa][i].v,w=G[fa][i].w;
	            if(v==u)continue;
	            if(c_back[v]-w*2>0){
					if(c_back[fa]-c_back[v]+w+c[v]>c[fa])choose[fa]=v;
	            	c[fa]=max(c[fa],c_back[fa]-c_back[v]+w+c[v]);
	            }
	            else {
					if(c_back[fa]+c[v]-w>c[fa])choose[fa]=v;
					c[fa]=max(c[fa],c_back[fa]+c[v]-w);
				}
			}
        }
    }
    if(c_back[fa]-2*last>0)c[u]+=(c_back[fa]-2*last);
    if(c_back[fa]-last*2>0)c[u]=max(c[u],c_back[u]-c_back[fa]+last+c[fa]);
    else c[u]=max(c[u],c_back[u]+c[fa]-last);
    ans[u]=c[u];
    for(int i=0;i<G[u].size();i++){
        int v=G[u][i].v,w=G[u][i].w;
        if(v==fa)continue;
        dfs2(v,u,w);
    }
    if(fa!=-1){
		c_back[fa]=re;
    	c[fa]=re_c;
    	choose[fa]=rechoose;
    }
    c_back[u]=re_;
    c[u]=re_c_;
    choose[u]=rechoose_;
}

int main(){
    scanf("%d",&T);
    for(int t=1;t<=T;t++){
        scanf("%d",&n);
        for(int i=1;i<=n;i++)scanf("%d",&val[i]);
        for(int i=1;i<n;i++){
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            G[u].push_back((edge){v,w});
            G[v].push_back((edge){u,w});
        }
        dfs(1,-1);
        for(int i=1;i<=n;i++)c[i]+=val[i],c_back[i]+=val[i];
        dfs2(1,-1,0);
        printf("Case #%d:\n",t);
        for(int i=1;i<=n;i++)printf("%d\n",ans[i]);
        for(int i=1;i<=n;i++)G[i].clear(),c[i]=c_back[i]=choose[i]=0;
    }
    return 0;
}

/*
1
5
4 1 7 7 7 
1 2 6
1 3 1
2 4 8
3 5 2
*/

/*
1
9
22 78 78 43 86 90 96 27 31
1 2 50
2 3 49
2 4 6
3 5 80
1 6 23
1 7 93
3 8 66
3 9 61
*/