Codeforces Round #168 (Div. 1) B. Zero Tree(树上DFS)

来源:互联网 发布:csgo淘宝买枪 编辑:程序博客网 时间:2024/05/16 00:39
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 %I64d specifier.

Examples
input
31 21 31 -1 1
output
3
题目大意:有一棵点有权值的一棵树,现在对任意一个联通的子树进行+1或者-1,但是必须每次修改包含1点,要求算出最小操作次数
解题思路:这道题对于子树的重新定义是这道题的关键,然后对于这棵树来说,我们可以固定1为根,我们每次从叶子节点进行操作,对于一个父亲节点来说,它存在着一个++或者--的操作次数,对于有多个子节点的父亲节点来说,每次对于++和--都同时取MAX,然后累加到该节点上,一直重复到1节点

阅读全文
0 0
原创粉丝点击