CF 168 B Zero Tree(树形dp)

B. Zero Tree
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

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:

  1. Select the subtree of the given tree that includes the vertex with number 1.
  2. 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 ≤ nai ≠ 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 cincout streams or the %I64dspecifier.

Sample test(s)
input
3
1 2
1 3
1 -1 1
output
3


#pragma comment(linker, "/STACK:1024000000,1024000000")
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)

#define bug printf("hihi\n")

#define eps 1e-8
typedef __int64 ll;

using namespace std;


#define INF 0x3f3f3f3f
#define N 100005
ll down[N],up[N];
int n;
int head[N];
int num;
struct stud{
  int to,ne;
}e[N*2];
ll va[N];

inline void add(int u,int v)
{
     e[num].to=v;
     e[num].ne=head[u];
     head[u]=num++;
}

void dfs(int u,int pre)
{
    for(int i=head[u];i!=-1;i=e[i].ne)
    {
        int to=e[i].to;
        if(to==pre) continue;
        dfs(to,u);
        down[u]=max(down[u],down[to]);
        up[u]=max(up[u],up[to]);
    }
    va[u]=va[u]-down[u]+up[u];
    if(va[u]>0) down[u]+=va[u];
    else up[u]-=va[u];
}

int main()
{
   int i,j;
   while(~scanf("%d",&n))
   {
       int u,v;
       memset(head,-1,sizeof(head));
       num=0;
       i=n-1;
       while(i--)
       {
           scanf("%d%d",&u,&v);
           add(u,v);
           add(v,u);
       }
       for(i=1;i<=n;i++)
        scanf("%I64d",&va[i]);
       memset(down,0,sizeof(down));
       memset(up,0,sizeof(up));
       dfs(1,-1);
       printf("%I64d\n",down[1]+up[1]);
   }
   return 0;
}



你可能感兴趣的:(DP,动态规划)