Uncle Bogdan and Country Happiness (Codeforces 1388C)
Tags: Greedy, trees

Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$n−1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".

Input: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases.The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$) — the number of cities and citizens.The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city.The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city.Next $$$n − 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road.It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output: For each test case, print YES, if the collected data is correct, or NO — otherwise. You can print characters in YES or NO in any case.

Note: Let's look at the first test case of the first sample:   At first, all citizens are in the capital. Let's describe one of possible scenarios:   a person from city $$$1$$$: he lives in the capital and is in good mood;  a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$;  a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood;  a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$;  In total,   $$$h_1 = 4 - 0 = 4$$$,  $$$h_2 = 0$$$,  $$$h_3 = 1 - 1 = 0$$$,  $$$h_4 = 0 - 1 = -1$$$,  $$$h_5 = 0$$$,  $$$h_6 = 0 - 1 = -1$$$,  $$$h_7 = 0$$$. The second case of the first test:   All people have already started in bad mood in the capital — this is the only possible scenario.The first case of the second test:   The second case of the second test:   It can be proven that there is no way to achieve given happiness indexes in both cases of the second test. 

Sample Inputs:
2
7 4
1 0 1 1 0 1 0
4 0 0 -1 0 -1 0
1 2
1 3
1 4
3 5
3 6
3 7
5 11
1 2 5 2 1
-11 -2 -6 -2 -1
1 2
1 3
1 4
3 5

2
4 4
1 1 1 1
4 1 -3 -1
1 2
1 3
1 4
3 13
3 3 7
13 1 4
1 2
1 3

Sample Outputs:
YES
YES

NO
NO

Solution (Python):
class UnionFind:

    def __init__(self, n):
        self.p = list(range(n))
        self.rank = [0] * n

    def find(self, x):
        if x != self.p[x]:
            self.p[x] = self.find(self.p[x])
        return self.p[x]

    def union(self, x, y):
        (px, py) = (self.find(x), self.find(y))
        if px == py:
            return 0
        self.p[py] = px
        self.rank[px] += self.rank[py]
        return 1
from types import GeneratorType

def cache(f, queue=[]):

    def wrappedfunc(*args, **kwargs):
        if queue:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if isinstance(to, GeneratorType):
                    queue.append(to)
                    to = next(to)
                else:
                    if not queue:
                        break
                    queue.pop()
                    if not queue:
                        break
                    to = queue[-1].send(to)
            return to
    return wrappedfunc

def query(x, y):
    print('?', x, y, flush=True)
    return int(input())

def main():
    """"""

    def f(p, pp):
        tot = P[p]
        ch = 0
        tots = 0
        for c in G[p]:
            if c != pp:
                (h, s, totc) = f(c, p)
                if h == -1 and s == -1 and (totc == -1):
                    return [-1, -1, -1]
                tot += totc
                ch += h
                tots += s
        if (H[p] + tot) % 2:
            return [-1, -1, -1]
        ph = (H[p] + tot) // 2
        if not (ph >= 0 and ph <= tot) or ch > ph:
            return [-1, -1, -1]
        return [ph, tot - ph, tot]
    for _ in range(int(input())):
        (n, m) = I()
        P = list(I())
        H = list(I())
        G = {i: [] for i in range(n)}
        for _ in range(n - 1):
            (x, y) = I()
            x -= 1
            y -= 1
            G[x].append(y)
            G[y].append(x)
        (h, s, p) = f(0, -1)
        if h == -1 and s == -1 and (p == -1):
            print('NO')
        else:
            print('YES')
import sys
import threading
sys.setrecursionlimit(500000)
I = lambda : map(int, input().split())
input = sys.stdin.readline
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()

Solution (Python):
import sys
sys.setrecursionlimit(1000000)
input = sys.stdin.buffer.readline
t = int(input())
for zzz in range(t):
    (n, m) = [int(x) for x in input().split()]
    p = [int(x) for x in input().split()]
    h = [int(x) for x in input().split()]
    p.insert(0, 0)
    h.insert(0, 0)
    edges = [[] for _ in range(n + 1)]
    for zz in range(n - 1):
        (u, v) = [int(x) for x in input().split()]
        edges[u].append(v)
        edges[v].append(u)
    ok = [True]

    def dfs(node, parent):
        T = p[node]
        minH = 0
        for nextt in edges[node]:
            if nextt != parent:
                (a, b) = dfs(nextt, node)
                T += a
                minH += b
        temp = h[node] + T
        if temp % 2 == 1:
            ok[0] = False
        actualH = temp // 2
        actualS = T - actualH
        if actualH < 0 or actualS < 0:
            ok[0] = False
        if actualH < minH:
            ok[0] = False
        return (T, actualH)
    dfs(1, 0)
    if ok[0]:
        print('YES')
    else:
        print('NO')

Solution (Python):
class UnionFind:

    def __init__(self, n):
        self.p = list(range(n))
        self.rank = [0] * n

    def find(self, x):
        if x != self.p[x]:
            self.p[x] = self.find(self.p[x])
        return self.p[x]

    def union(self, x, y):
        (px, py) = (self.find(x), self.find(y))
        if px == py:
            return 0
        self.p[py] = px
        self.rank[px] += self.rank[py]
        return 1
from types import GeneratorType

def cache(f, queue=[]):

    def wrappedfunc(*args, **kwargs):
        if queue:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if isinstance(to, GeneratorType):
                    queue.append(to)
                    to = next(to)
                else:
                    if not queue:
                        break
                    queue.pop()
                    if not queue:
                        break
                    to = queue[-1].send(to)
            return to
    return wrappedfunc

def query(x, y):
    print('?', x, y, flush=True)
    return int(input())

def main():
    """"""

    def f(p, pp):
        if not G[p]:
            if abs(H[p]) <= P[p] and (P[p] % 2 and H[p] % 2 or (P[p] % 2 == 0 and H[p] % 2 == 0)):
                return [(H[p] + P[p]) // 2, P[p] - (H[p] + P[p]) // 2, P[p]]
            else:
                return [-1, -1, -1]
        tot = P[p]
        ch = 0
        tots = 0
        for c in G[p]:
            if c != pp:
                (h, s, totc) = f(c, p)
                if h == -1 and s == -1 and (totc == -1):
                    return [-1, -1, -1]
                tot += totc
                ch += h
                tots += s
        if (H[p] + tot) % 2:
            return [-1, -1, -1]
        ph = (H[p] + tot) // 2
        if abs(H[p]) > tot or ch > ph or (tot % 2 and H[p] % 2 == 0 or (tot % 2 == 0 and H[p] % 2)):
            return [-1, -1, -1]
        return [ph, tot - ph, tot]
    for _ in range(int(input())):
        (n, m) = I()
        P = list(I())
        H = list(I())
        G = {i: [] for i in range(n)}
        for _ in range(n - 1):
            (x, y) = I()
            x -= 1
            y -= 1
            G[x].append(y)
            G[y].append(x)
        (h, s, p) = f(0, -1)
        if h == -1 and s == -1 and (p == -1):
            print('NO')
        else:
            print('YES')
import sys
import threading
sys.setrecursionlimit(500000)
I = lambda : map(int, input().split())
input = sys.stdin.readline
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()