CodeForces 274B Zero Tree

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.

Example
Input
3
1 2
1 3
1 -1 1
Output

3


树形dp

#include 
#include   
using namespace std;
const int N = 2e5 + 5;
int n, sz, x, y;
int ft[N], nt[N], u[N], v[N];
long long dp[N][2];

void dfs(int x, int fa)
{
	for (int i = ft[x]; ~i; i = nt[i])
	{
		if (u[i] == fa) continue;
		dfs(u[i], x);
		dp[x][0] = max(dp[x][0], dp[u[i]][0]);
		dp[x][1] = max(dp[x][1], dp[u[i]][1]);
	}
	long long now = v[x] - dp[x][0] + dp[x][1];
	dp[x][0] += now > 0 ? now : 0;
	dp[x][1] += now < 0 ? -now : 0;
}

int main()
{
	while (~scanf("%d", &n))
	{
		sz = 0;
		for (int i = 1; i <= n; i++) ft[i] = -1;
		for (int i = 1; i < n; i++)
		{
			scanf("%d%d", &x, &y);
			u[sz] = y; nt[sz] = ft[x]; ft[x] = sz++;
			u[sz] = x; nt[sz] = ft[y]; ft[y] = sz++;
		}
		for (int i = 1; i <= n; i++) scanf("%d", &v[i]);
		dfs(1, 0); printf("%lld\n", dp[1][0] + dp[1][1]);
	}
	return 0;
}


你可能感兴趣的:(Codeforces,----树形dp)