Zero Tree (Codeforces 275D)
Tags: DP, trees

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.


Sample Inputs:
3
1 2
1 3
1 -1 1

Sample Outputs:
3

Solution (Python):
from collections import defaultdict, Counter, deque
import threading
import sys
input = sys.stdin.readline

def ri():
    return int(input())

def rs():
    return input()

def rl():
    return list(map(int, input().split()))

def rls():
    return list(input().split())
threading.stack_size(10 ** 8)
sys.setrecursionlimit(10 ** 6)

def main():
    n = ri()
    g = defaultdict(list)
    for _ in range(n - 1):
        (u, v) = rl()
        g[u].append(v)
        g[v].append(u)
    v = [0] + rl()
    req = [[0, 0] for _ in range(n + 1)]

    def dfs(cn, par):
        for nn in g[cn]:
            if nn != par:
                dfs(nn, cn)
                req[cn][0] = max(req[cn][0], req[nn][0])
                req[cn][1] = max(req[cn][1], req[nn][1])
        val = v[cn] + req[cn][0] - req[cn][1]
        if val >= 0:
            req[cn][1] += val
        else:
            req[cn][0] -= val
    dfs(1, -1)
    print(sum(req[1]))
    pass
threading.Thread(target=main).start()

Solution (Python):
import sys

def minp():
    return sys.stdin.readline().strip()
n = int(minp())
e = [0]
p = [None] * (n + 1)
for i in range(n):
    e.append([])
for i in range(n - 1):
    (a, b) = map(int, minp().split())
    e[a].append(b)
    e[b].append(a)
v = list(map(int, minp().split()))
plus = [0] * (n + 1)
minus = [0] * (n + 1)
was = [False] * (n + 1)
was[1] = True
i = 0
j = 1
q = [0] * (n + 100)
q[0] = 1
p[1] = 0
while i < j:
    x = q[i]
    i += 1
    for y in e[x]:
        if not was[y]:
            was[y] = True
            p[y] = x
            q[j] = y
            j += 1
i = j - 1
while i >= 0:
    x = q[i]
    i -= 1
    s = minus[x] - plus[x]
    z = v[x - 1] + s
    pp = p[x]
    minus[pp] = max(minus[x], minus[pp])
    plus[pp] = max(plus[x], plus[pp])
    if z > 0:
        plus[pp] = max(plus[pp], plus[x] + z)
    elif z < 0:
        minus[pp] = max(minus[pp], minus[x] - z)
print(plus[0] + minus[0])

Solution (Python):
from collections import defaultdict
from sys import stdin, setrecursionlimit
setrecursionlimit(10 ** 6)
import threading

def dfs(g, node, parent, cr, req):
    l = [0, 0]
    for i in g[node]:
        if i != parent:
            t = dfs(g, i, node, cr, req)
            l[0] = max(t[0], l[0])
            l[1] = max(t[1], l[1])
    if l[0] - l[1] <= req[node]:
        l[0] += req[node] - (l[0] - l[1])
    else:
        l[1] += l[0] - l[1] - req[node]
    return l

def main():
    n = int(input())
    g = defaultdict(list)
    for i in range(n - 1):
        (a, b) = map(int, input().strip().split())
        g[a - 1].append(b - 1)
        g[b - 1].append(a - 1)
    req = list(map(int, input().strip().split()))
    cr = [0]
    x = dfs(g, 0, -1, cr, req)
    print(sum(x))
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()