XDU 1164 男神的树(树+lazy数组)

#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#define N (int)(1e7+5)
using namespace std;
int fa[N],va[N],lazy[N];
bool vis[N];
int n,u,v;
long long sum;
long long dfs(int i)
{
    if(vis[i])
        return 0;
    vis[i]=1;
    if(fa[i]==0){
        lazy[i]+=va[i];
        return abs(lazy[i]);
    }
    long long s=0;
    va[i]-=lazy[fa[i]];
    lazy[i]+=(lazy[fa[i]]+va[i]);
    s+=abs(va[i]);
    return s; 
}
int main()
{
    scanf("%d",&n);
    for(int i=0;i<n-1;++i){
        scanf("%d%d",&u,&v);
        fa[v]=u;
    }
    for(int i=1;i<=n;++i)
        scanf("%d",&va[i]);
    for(int i=1;i<=n;++i)
        sum+=dfs(i);
    printf("%lld\n",sum);
}

 

posted @ 2017-02-17 16:50  despair_ghost  阅读(274)  评论(0编辑  收藏  举报