CodeForces 274 B.Zero Tree(树形dp)

B.Zero Tree

A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.

A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.

You’re given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation:

Select the subtree of the given tree that includes the vertex with number 1.
Increase (or decrease) by one all the integers which are written on the vertices of that subtree.
Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.

Input

The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there’s an edge between vertices ai and bi. It’s guaranteed that the input graph is a tree.

The last line of the input contains a list of n space-separated integers v1, v2, …, vn (|vi| ≤ 109).

Output

Print the minimum number of operations needed to solve the task.

Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Examples

Input

3
1 2
1 3
1 -1 1

Output

3

思路:

因为每次修改都必须经过点1,所以将点1作为树根开始dfs
因为1是根,所以每次修改一个点,该点到根路径上的点全部都会被做相同的修改

add[i]表示i点增加的次数
del[i]表示i点减小的次数
a[i]表示i点的值

显然当前点的add和del肯定大于等于子节点的add和del
因为当前节点在子节点到根的路径上,所以子节点的修改一定也会施加到当前点。
所以先对于所有子节点v:add[x]=max(add[v]),del[x]=max(del[v])
先计算一下结果:a[x]+=add[x],a[x]-=del[x]
如果a[x]不为0,则a[x]还需要修改,如果大于0则del[x]+=a[x],否则add[x]+=(-a[x])

一直搜到根点1,最后的答案为add[1]+del[1]

code:

#include
using namespace std;
#define int long long
const int maxm=1e5+5;
vector<int>g[maxm];
int add[maxm];
int del[maxm];
int a[maxm];
int n;
void dfs(int x,int fa){
     
    for(int v:g[x]){
     
        if(v==fa)continue;
        dfs(v,x);
        add[x]=max(add[x],add[v]);
        del[x]=max(del[x],del[v]);
    }
    a[x]+=add[x];
    a[x]-=del[x];
    if(a[x]>0){
     
        del[x]+=a[x];
    }else{
     
        add[x]+=(-a[x]);
    }
}
signed main(){
     
    cin>>n;
    for(int i=1;i<n;i++){
     
        int a,b;
        cin>>a>>b;
        g[a].push_back(b);
        g[b].push_back(a);
    }
    for(int i=1;i<=n;i++){
     
        cin>>a[i];
    }
    dfs(1,-1);
    cout<<add[1]+del[1]<<endl;
    return 0;
}

你可能感兴趣的:(CodeForces 274 B.Zero Tree(树形dp))