Problem:
 Score : 800 points    Problem Statement We have a tree with N vertices. The vertices are numbered 1, 2, ..., N . The i -th ( 1 ≦ i ≦ N - 1 ) edge connects the two vertices A_i and B_i .  Takahashi wrote integers into K of the vertices. Specifically, for each 1 ≦ j ≦ K , he wrote the integer P_j into vertex V_j . The remaining vertices are left empty. After that, he got tired and fell asleep.  Then, Aoki appeared. He is trying to surprise Takahashi by writing integers into all empty vertices so that the following condition is satisfied:   Condition: For any two vertices directly connected by an edge, the integers written into these vertices differ by exactly 1 .   Determine if it is possible to write integers into all empty vertices so that the condition is satisfied. If the answer is positive, find one specific way to satisfy the condition.      Constraints  1 ≦ N ≦ 10^5  1 ≦ K ≦ N  1 ≦ A_i, B_i ≦ N ( 1 ≦ i ≦ N - 1 )  1 ≦ V_j ≦ N ( 1 ≦ j ≦ K ) (21:18, a mistake in this constraint was corrected)  0 ≦ P_j ≦ 10^5 ( 1 ≦ j ≦ K )  The given graph is a tree.  All v_j are distinct.         Input The input is given from Standard Input in the following format:  N  A_1  B_1  A_2  B_2  :  A_{N-1}  B_{N-1}  K  V_1  P_1  V_2  P_2  :  V_K  P_K       Output If it is possible to write integers into all empty vertices so that the condition is satisfied, print Yes . Otherwise, print No .  If it is possible to satisfy the condition, print N lines in addition. The v -th ( 1 ≦ v ≦ N ) of these N lines should contain the integer that should be written into vertex v . If there are multiple ways to satisfy the condition, any of those is accepted.        Sample Input 1 5
1 2
3 1
4 3
3 5
2
2 6
5 7      Sample Output 1 Yes
5
6
6
5
7  The figure below shows the tree when Takahashi fell asleep. For each vertex, the integer written beside it represents the index of the vertex, and the integer written into the vertex is the integer written by Takahashi.     Aoki can, for example, satisfy the condition by writing integers into the remaining vertices as follows:     This corresponds to Sample Output 1. Note that other outputs that satisfy the condition will also be accepted, such as:  Yes
7
6
8
7
7       Sample Input 2 5
1 2
3 1
4 3
3 5
3
2 6
4 3
5 7      Sample Output 2 No       Sample Input 3 4
1 2
2 3
3 4
1
1 0      Sample Output 3 Yes
0
-1
-2
-3  The integers written by Aoki may be negative or exceed 10^6 .

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)


def dfs(v, parent, odd):
    hi = INF
    lo = -INF
    if fixed[v] != INF:
        if odd_even[v] != odd:
            print('No')
            exit()
        hi = lo = fixed[v]
    for u in links[v]:
        if u == parent:
            continue
        chi, clo = dfs(u, v, odd ^ 1)
        if hi < clo or chi < lo:
            print('No')
            exit()
        hi = min(hi, chi)
        lo = max(lo, clo)
    upper[v] = hi
    lower[v] = lo
    return hi + 1, lo - 1


def fill(v, parent, pp):
    if pp + 1 > upper[v]:
        assert pp - 1 >= lower[v]
        vp = fixed[v] = pp - 1
    else:
        vp = fixed[v] = pp + 1
    for u in links[v]:
        if u == parent:
            continue
        fill(u, v, vp)


inp = list(map(int, sys.stdin.buffer.read().split()))
n = inp[0]
links = [set() for _ in range(n)]
for a, b in zip(inp[1:2 * n - 1:2], inp[2:2 * n - 1:2]):
    a -= 1
    b -= 1
    links[a].add(b)
    links[b].add(a)
INF = 10 ** 9
k = inp[2 * n - 1]
fixed = [INF] * n
odd_even = {}
fixed_v = 0
for v, p in zip(inp[2 * n::2], inp[2 * n + 1::2]):
    v -= 1
    fixed[v] = p
    odd_even[v] = p % 2
    fixed_v = v

lower = [-INF] * n
upper = [INF] * n
dfs(fixed_v, -1, odd_even[fixed_v])
fill(fixed_v, -1, fixed[fixed_v] + 1)
print('Yes')
print('\n'.join(map(str, fixed)))

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

N = int(input())
G = [[] for _ in range(N+1)]
for _ in range(N-1):
    A, B = map(int, input().split())
    G[A].append(B)
    G[B].append(A)
K = int(input())
num = [-1] * (N+1)
for _ in range(K):
    V, P = map(int, input().split())
    num[V] = P


stack = [1]
depth = [-1] * (N+1)
depth[1] = 0
while stack:
    v = stack.pop()
    for c in G[v]:
        if depth[c] == -1:
            depth[c] = depth[v] + 1
            stack.append(c)
parity = [set(), set()]
for i in range(1, N+1):
    if num[i] != -1:
        parity[depth[i] % 2].add(num[i] % 2)
if len(parity[0]) == 2 or len(parity[1]) == 2:
    print('No')
    exit()

INF = 10**9
lb = [-INF] * (N+1)
ub = [INF] * (N+1)

def dfs1(v, p):
    for c in G[v]:
        if c == p:
            continue
        dfs1(c, v)
        lb[v] = max(lb[v], lb[c] - 1)
        ub[v] = min(ub[v], ub[c] + 1)
    if num[v] != -1:
        lb[v] = ub[v] = num[v]

dfs1(1, 0)

def dfs2(v, p):
    if lb[v] > ub[v]:
        print('No')
        exit()
    for c in G[v]:
        if c == p:
            continue
    for c in G[v]:
        if c == p:
            continue
        lb[c] = max(lb[c], lb[v] - 1)
        ub[c] = min(ub[c], ub[v] + 1)
        if lb[c] <= num[v] - 1:
            num[c] = num[v] - 1
        else:
            num[c] = num[v] + 1
        dfs2(c, v)

num[1] = lb[1]
dfs2(1, 0)
print('Yes')
print(*num[1:], sep='\n')

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

N = int(input())
G = [[] for _ in range(N+1)]
for _ in range(N-1):
    A, B = map(int, input().split())
    G[A].append(B)
    G[B].append(A)
K = int(input())
num = [-1] * (N+1)
for _ in range(K):
    V, P = map(int, input().split())
    num[V] = P


stack = [1]
depth = [-1] * (N+1)
depth[1] = 0
while stack:
    v = stack.pop()
    for c in G[v]:
        if depth[c] == -1:
            depth[c] = depth[v] + 1
            stack.append(c)
parity = [set(), set()]
for i in range(1, N+1):
    if num[i] != -1:
        parity[depth[i] % 2].add(num[i] % 2)
if len(parity[0]) == 2 or len(parity[1]) == 2:
    print('No')
    exit()

INF = 10**9
lb = [-INF] * (N+1)
ub = [INF] * (N+1)

def dfs1(v, p):
    for c in G[v]:
        if c == p:
            continue
        dfs1(c, v)
        lb[v] = max(lb[v], lb[c] - 1)
        ub[v] = min(ub[v], ub[c] + 1)
    if num[v] != -1:
        lb[v] = ub[v] = num[v]

dfs1(1, 0)

def dfs2(v, p):
    for c in G[v]:
        if c == p:
            continue
    for c in G[v]:
        if c == p:
            continue
        lb[c] = max(lb[c], lb[v] - 1)
        ub[c] = min(ub[c], ub[v] + 1)
        dfs2(c, v)

dfs2(1, 0)

for i in range(1, N+1):
    if lb[i] > ub[i]:
        print('No')
        exit()

print('Yes')

def dfs3(v, p):
    for c in G[v]:
        if c == p:
            continue
        if lb[c] <= num[v] - 1:
            num[c] = num[v] - 1
        else:
            num[c] = num[v] + 1
        dfs3(c, v)

num[1] = lb[1]
dfs3(1, 0)

print(*num[1:], sep='\n')

Solution (Python):
class Tree():
    def __init__(self, n, edge, indexed=1):
        self.n = n
        self.tree = [[] for _ in range(n)]
        for e in edge:
            self.tree[e[0] - indexed].append(e[1] - indexed)
            self.tree[e[1] - indexed].append(e[0] - indexed)

    def setroot(self, root):
        self.root = root
        self.parent = [None for _ in range(self.n)]
        self.parent[root] = -1
        self.depth = [None for _ in range(self.n)]
        self.depth[root] = 0
        self.order = []
        self.order.append(root)
        stack = [root]
        while stack:
            node = stack.pop()
            for adj in self.tree[node]:
                if self.parent[adj] is None:
                    self.parent[adj] = node
                    self.depth[adj] = self.depth[node] + 1
                    self.order.append(adj)
                    stack.append(adj)

INF = 10**18

import sys
input = sys.stdin.readline

N = int(input())
E = [tuple(map(int, input().split())) for _ in range(N - 1)]

num = [None for _ in range(N)]

K = int(input())

for _ in range(K):
    v, p = map(int, input().split())
    num[v - 1] = p

tree = Tree(N, E)
tree.setroot(v - 1)

even = []
odd = []

for i in range(N):
    if num[i] is not None:
        if tree.depth[i] % 2 == 0:
            even.append(num[i] % 2)
        else:
            odd.append(num[i] % 2)

if not ((all(even) or not any(even)) and (all(odd) or not any(odd))):
    print('No')

else:
    I = [[-INF, INF] for _ in range(N)]
    for i in range(N):
        if num[i] is not None:
            I[i] = [num[i], num[i]]
    for node in tree.order[::-1]:
        lt, rt = I[node]
        for adj in tree.tree[node]:
            lt = max(lt, I[adj][0] - 1)
            rt = min(rt, I[adj][1] + 1)
        if lt > rt:
            print('No')
            break
        I[node] = [lt, rt]

    else:
        stack = [v - 1]
        visited = [0 for _ in range(N)]
        visited[v - 1] = 1
        while stack:
            node = stack.pop()
            for adj in tree.tree[node]:
                if visited[adj]:
                    continue
                visited[adj] = 1
                if I[adj][0] <= num[node] - 1 <= I[adj][1]:
                    num[adj] = num[node] - 1
                elif I[adj][0] <= num[node] + 1 <= I[adj][1]:
                    num[adj] = num[node] + 1
                else:
                    print('No')
                    break
                stack.append(adj)
            else:
                continue
            break
        else:
            print('Yes')
            print('\n'.join(map(str, num)))

Solution (Python):
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

N = int(input())
edge = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    edge[a].append(b)
    edge[b].append(a)

K = int(input())
res = [-1]*N
for i in range(K):
    v, p = map(int, input().split())
    v -= 1
    if i == 0:
        root = v
    res[v] = p



dist = [-1] * N
parent = [-1] * N
dist[root] = 0
order = []
node = [root]
bm = (dist[root] ^ res[root]) & 1
while node:
    s = node.pop()
    order.append(s)
    if res[s] != -1 and bm != (dist[s] ^ res[s]) & 1:
        print("No")
        exit()
    for t in edge[s]:
        if dist[t] != -1:
            continue
        parent[t] = s
        dist[t] = dist[s] + 1
        node.append(t)

inf = 10**18
inf = float("inf")
U = [inf] * N
L = [-inf] * N
for v in order[::-1]:
    if res[v] != -1:
        if res[v] < L[v] or U[v] < res[v]:
            print("No")
            exit()
        U[v] = res[v]
        L[v] = res[v]

    if v != root:
        p = parent[v]
        if L[v] - 1 > U[p] or U[v] + 1 < L[p]:
            print("No")
            exit()
        L[p] = max(L[p], L[v] - 1)
        U[p] = min(U[p], U[v] + 1)

for v in order[1:]:
    p = parent[v]
    if L[v] <= res[p] + 1 <= U[v]:
        res[v] = res[p] + 1
    else:
        res[v] = res[p] - 1

print("Yes")
print(*res, sep="\n")

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
e = [[] for _ in range(N + 1)]
for _ in range(N - 1):
  u, v = map(int, input().split())
  e[u].append(v)
  e[v].append(u)

s = [1]
color = [0] * (N + 1)
color[1] = 1
while len(s):
  x = s.pop()
  for y in e[x]:
    if color[y]:
      if color[x] == color[y]: break
      continue
    s.append(y)
    color[y] = color[x] ^ 2
  else: continue
  print("No")
  exit(0)
res = [-1] * (N + 1)
mx = 0
for _ in range(int(input())):
  v, p = map(int, input().split())
  res[v] = p
  mx = max(mx, p)
table = [[] for _ in range(mx + 1 + N + 1)]
for i in range(N + 1):
  if res[i] != -1: table[res[i]].append(i)

for i in range(mx + N + 1):
  while len(table[i]):
    x = table[i].pop()
    for y in e[x]:
      if res[y] == -1:
        res[y] = res[x] + 1
        table[i + 1].append(y)
      elif abs(res[x] - res[y]) != 1:
        break
    else: continue
    break
  else: continue
  break
else:
  print("Yes")
  for r in res[1: ]: print(r)
  exit(0)
print("No")

Solution (Python):


import sys
read = sys.stdin.read
readline = sys.stdin.readline

n, = map(int,readline().split())

g = [[] for _ in range(n)]
for _ in range(n-1):
    a,b = map(int,readline().split())
    g[a-1].append(b-1)
    g[b-1].append(a-1)
    

order = []
parent = [-1]*n
st = [0]
while st:
    v = st.pop()
    order.append(v)
    for c in g[v]:
        if parent[v] != c:
            parent[c] = v
            st.append(c)

INF = 1<<30
high = [INF]*n
low = [-INF]*n
val = [INF]*n

k, = map(int,readline().split())
for _ in range(k):
    v,p = map(int,readline().split())
    high[v-1] = low[v-1] = val[v-1] = p

for v in order[:0:-1]:
    p = parent[v]
    
    h,l = high[v]+1,low[v]-1
    
    if h >= INF:
        pass
    elif high[p]>=INF:
        high[p] = h
        low[p] = l
    elif (high[p]-h)&1==0: 
        if h < high[p]: high[p] = h
        if l > low[p]: low[p] = l
        if high[p] < low[p]:
            print("No")
            break
    else: 
        print("No")
        break
    
    
else: 
    print("Yes")
    for v in order:
        if val[v] == INF:
            val[v] = low[v]
        for c in g[v]:
            high[c] = min(high[c],val[v]+1)
            low[c] = max(low[c],val[v]-1)
    
    
    print(*val,sep="\n")

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

INF = 10**10
n = int(input())
T = [[] for _ in range(n+1)]
for _ in range(n-1):
  a, b = map(int, input().split())
  T[a].append(b)
  T[b].append(a)
k = int(input())
VP = tuple(tuple(map(int, input().split())) for _ in range(k))
P = [-1]*(n+1)
A = [-1]*(n+1)
r, c = VP[0]
for v, p in VP:
  P[v] = p
def dfs1(v, par=-1, color=c%2):
  if P[v] == -1:
    l = -INF
    r = INF
  else:
    l = P[v]
    r = P[v]
  for nv in T[v]:
    if nv == par:
      continue
    nl, nr = dfs1(nv, v, color^1)
    l = max(l, nl-1)
    r = min(r, nr+1)
  if l&1 ^ color:
    l += 1
  if r&1 ^ color:
    r -= 1
  if l > r:
    print("No")
    exit()
  P[v] = (l, r)
  return P[v]
dfs1(r)
def dfs2(v, ini, par=-1):
  l, r = P[v]
  if l == r:
    A[v] = l
  else:
    if l <= ini-1 <= r:
      A[v] = ini-1
    else:
      A[v] = ini+1
  for nv in T[v]:
    if nv == par:
      continue
    dfs2(nv, A[v], v)
dfs2(r, P[r][0])
print("Yes")
print(*A[1:], sep="\n")

Solution (Python):
import heapq
import sys
input = sys.stdin.readline
INF = 10 ** 18


n = int(input())
edges = [list(map(int, input().split())) for i in range(n - 1)]
k = int(input())
info = [list(map(int, input().split())) for i in range(k)]

tree = [[] for i in range(n)]
for a, b in edges:
    a -= 1
    b -= 1
    tree[a].append(b)
    tree[b].append(a)

ans = [INF] * n
q = []
for v, val in info:
    v -= 1
    ans[v] = val
    heapq.heappush(q, (-val, v))
    for nxt_v in tree[v]:
        if ans[nxt_v] != INF and abs(ans[v] - ans[nxt_v]) != 1:
            print("No")
            exit()

while q:
    val, v = heapq.heappop(q)
    val = -val
    for nxt_v in tree[v]:
        if ans[nxt_v] == INF:
            ans[nxt_v] = val - 1
            heapq.heappush(q, (-(val - 1), nxt_v))
        else:
            if abs(ans[v] - ans[nxt_v]) != 1:
                print("No")
                exit()

print("Yes")
for val in ans:
    print(val)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul

mod = 10 ** 9 + 7
sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
G = [[] for _ in range(n)]
for _ in range(n - 1):
    a, b = LI()
    G[a - 1] += [b - 1]
    G[b - 1] += [a - 1]

cond = [(-INF, INF) for _ in range(n)]
k = I()
for _ in range(k):
    v, p = LI()
    cond[v - 1] = (p, p)

ans = [0] * n
visited = [0] * n
def f(u):
    visited[u] = 1
    max_ret = cond[u][1]
    min_ret = cond[u][0]
    u_flg = max_ret % 2 if max_ret == min_ret else -1
    for v in G[u]:
        if visited[v]:
            continue
        x, y, flg = f(v)
        if flg != -1 and u_flg == flg:
            print("No")
            exit()
        max_ret = min(max_ret, y + 1)
        min_ret = max(min_ret, x - 1)
    if min_ret > max_ret:
        print("No")
        exit()
    cond[u] = (min_ret, max_ret)
    return min_ret, max_ret, u_flg

f(0)
print("Yes")
visited = [0] * n
ans = [-1] * n
ans[0] = cond[0][0]
def f2(u):
    visited[u] = 1
    for v in G[u]:
        if visited[v]:
            continue
        ans[v] = ans[u] + 1 if cond[v][0] <= ans[u] + 1 <= cond[v][1] else ans[u] - 1
        f2(v)

f2(0)
print(*ans, sep="\n")

Solution (Python):
def N(): return int(input())
def NM():return map(int,input().split())
def L():return list(NM())
def LN(n):return [N() for i in range(n)]
def LL(n):return [L() for i in range(n)]
n=N()
edge=[[] for i in range(n+1)]
for i in range(n-1):
    a,b=map(int,input().split())
    edge[a].append(b)
    edge[b].append(a)
INF=float("inf")
ma=[INF]*(n+1)
mi=[-INF]*(n+1)
k=N()
vp=LL(k)
for v,p in vp:
    ma[v]=p
    mi[v]=p

import sys
sys.setrecursionlimit(10**6)
def dfs(v,d,hi,lo):
    dep[v]=d
    ma[v]=min(ma[v],hi)
    mi[v]=max(mi[v],lo)
    hi=ma[v]
    lo=mi[v]
    for i in edge[v]:
        if dep[i]==-1:
            hi,lo=dfs(i,d+1,hi+1,lo-1)
            ma[v]=min(ma[v],hi)
            mi[v]=max(mi[v],lo)
            hi=ma[v]
            lo=mi[v]
    return hi+1,lo-1
for i in range(2):
    dep=[-1 for i in range(n+1)]
    dfs(v,0,p,p)
for i,j in zip(mi,ma):
    if i>j or (i-j)%2==1:
        print("No")
        break
else:
    print("Yes")
    for i in mi[1:]:
        print(i)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    def imp():
        print("No")
        exit()

    n=II()
    to=[[] for _ in range(n)]
    for _ in range(n-1):
        u,v=MI1()
        to[u].append(v)
        to[v].append(u)
    k=II()
    pp=[-1]*n
    for _ in range(k):
        v,p=MI()
        pp[v-1]=p

    dp=[[-1,-1,-1] for _ in range(n)]

    def dfs(u=0,pu=-1):
        par=mn=mx=-1
        for v in to[u]:
            if v==pu:continue
            dfs(v,u)
            pv, mnv, mxv = dp[v]
            if pv==-1:continue
            if par==-1:par,mn,mx=1-pv,mnv-1,mxv+1
            else:
                if par^pv==0:imp()
                mn=max(mn,mnv-1)
                mx=min(mx,mxv+1)
                if mn>mx:imp()
        p=pp[u]
        if p==-1:dp[u]=[par,mn,mx]
        elif par!=-1 and (p&1!=par or p<mn or p>mx):imp()
        else:dp[u]=[p&1,p,p]

    dfs()
    
    for p0 in range(dp[0][1],dp[0][2]+1):
        if p0&1==dp[0][0]:
            pp[0]=p0
            break
    else:imp()

    def dfs2(u=0,pu=-1):
        if pp[u]==-1:
            p=pp[pu]
            for d in [1,-1]:
                if dp[u][0]==-1 or dp[u][1]<=p+d<=dp[u][2]:
                    pp[u]=p+d
                    break
        for v in to[u]:
            if v==pu:continue
            dfs2(v,u)

    dfs2()
    
    print("Yes")
    for p in pp:print(p)

main()

Solution (Python):
def main():
    n = int(input())
    ab = [list(map(int, input().split())) for _ in [0]*(n-1)]
    k = int(input())
    vp = [list(map(int, input().split())) for _ in [0]*k]

    g = [[] for _ in [0]*n]
    [g[a-1].append(b-1) for a, b in ab]
    [g[b-1].append(a-1) for a, b in ab]

    
    parity = [-1]*n
    root = vp[0][0]-1
    p = vp[0][1] % 2
    parity[root] = p
    q = [root]
    while q:  
        p ^= 1
        qq = []
        while q:
            i = q.pop()
            for j in g[i]:
                if parity[j] == -1:
                    parity[j] = p
                    qq.append(j)
        q = qq

    
    for v, p in vp:
        if p % 2 != parity[v-1]:
            print("No")
            return

    
    ans_range = [[-10**10, 10**10] for _ in [0]*n]
    q = [root]
    vp = {v-1: p for v, p in vp}
    M = 10**10
    m = -10**10
    g2 = [set(gg) for gg in g]
    while q:
        i = q[-1]
        if i in vp:
            if m <= vp[i] <= M:
                M = vp[i]
                m = M
                ans_range[i] = [m, M]
            else:
                print("No")
                return
        else:
            m2, M2 = ans_range[i]
            if M2 < m or M < m2:
                print("No")
                return
            m = max(m, m2)
            M = min(M, M2)
            ans_range[i] = [m, M]
        if g2[i]:
            j = g2[i].pop()
            g2[j].remove(i)
            q.append(j)
        else:
            q.pop()
        m -= 1
        M += 1

    q = [root]
    now = vp[root]
    ans = [None]*n
    g = [set(gg) for gg in g]
    while q:
        i = q[-1]
        if ans[i] != None:
            now = ans[i]
        else:
            if ans_range[i][1] < now:
                now -= 2
            ans[i] = now
        if g[i]:
            j = g[i].pop()
            g[j].remove(i)
            q.append(j)
        else:
            q.pop()
        now += 1
    print("Yes")
    for i in ans:
        print(i)


main()

Solution (Python):
def main():
    n = int(input())
    ab = [list(map(int, input().split())) for _ in [0]*(n-1)]
    k = int(input())
    vp = [list(map(int, input().split())) for _ in [0]*k]

    g = [[] for _ in [0]*n]
    [g[a-1].append(b-1) for a, b in ab]
    [g[b-1].append(a-1) for a, b in ab]

    
    parity = [-1]*n
    root = vp[0][0]-1
    p = vp[0][1] % 2
    parity[root] = p
    q = [root]
    while q:  
        p ^= 1
        qq = []
        while q:
            i = q.pop()
            for j in g[i]:
                if parity[j] == -1:
                    parity[j] = p
                    qq.append(j)
        q = qq

    
    for v, p in vp:
        if p % 2 != parity[v-1]:
            print("No")
            return

    
    ans_range = [[-10**10, 10**10] for _ in [0]*n]
    q = [root]
    vp = {v-1: p for v, p in vp}
    M = 10**10
    m = -10**10
    g2 = [set(gg) for gg in g]
    while q:
        i = q[-1]
        if i in vp:
            if m <= vp[i] <= M:
                M = vp[i]
                m = M
                ans_range[i] = [m, M]
            else:
                print("No")
                return
        else:
            m2, M2 = ans_range[i]
            if M2 < m or M < m2:
                print("No")
                return
            m = max(m, m2)
            M = min(M, M2)
            ans_range[i] = [m, M]
        if g2[i]:
            j = g2[i].pop()
            g2[j].remove(i)
            q.append(j)
        else:
            q.pop()
        m -= 1
        M += 1

    q = [root]
    now = vp[root]
    ans = [None]*n
    g = [set(gg) for gg in g]
    while q:
        i = q[-1]
        if ans[i] != None:
            now = ans[i]
        else:
            if ans_range[i][1] < now:
                now -= 2
            ans[i] = now
        if g[i]:
            j = g[i].pop()
            g[j].remove(i)
            q.append(j)
        else:
            q.pop()
        now += 1
    print("Yes")
    for i in ans:
        print(i)


main()

Solution (Python):
import sys
from collections import defaultdict as dd
from collections import deque as dq
import heapq
hpush = heapq.heappush
hpop = heapq.heappop
input = sys.stdin.readline
N = int(input())
e = dd(list)
for _ in range(N - 1):
  u, v = map(int, input().split())
  e[u].append(v)
  e[v].append(u)

K = int(input())
ls = [-10 ** 10] * (N + 1)
rs = [10 ** 10] * (N + 1)

Q = dq([])
h = []
res = [-10 ** 10] * (N + 1)
for _ in range(K):
  x, v = map(int, input().split())
  ls[x] = v
  rs[x] = v
  hpush(h, (v, x))
  res[x] = v
  Q.append(x)

vis = [0] * (N + 1)
while len(Q):
  x = Q.popleft()
  if vis[x]: continue
  vis[x] = 1
  for y in e[x]:
    ls[y] = max(ls[y], ls[x] - 1)
    rs[y] = min(rs[y], rs[x] + 1)
    if ls[y] % 2 == ls[x] % 2:
      print("No")
      exit(0)
    if vis[y]: continue
    Q.append(y)

for x in range(1, N + 1):
  if ls[x] > rs[x]:
    print("No")
    exit(0)


while len(h):
  _, x = hpop(h)
  for y in e[x]:
    if res[y] != -10 ** 10: continue
    res[y] = res[x] + 1
    hpush(h, (res[y], y))
  

print("Yes")
for r in res[1: ]: print(r)

Solution (Python):
import sys

input=sys.stdin.readline
sys.setrecursionlimit(1000000)

N=int(input())
edge={i:[] for i in range(1,N+1)}
for i in range(0,N-1):
    a,b=map(int,input().split())
    edge[a].append(b)
    edge[b].append(a)

K=int(input())
dic={}
for i in range(K):
    v,p=map(int,input().split())
    dic[v]=0
    dic[v]=p

memo={i:[] for i in range(1,N+1)}
flag={i:True for i in range(2,N+1)}
def dfs(num):
    flag[num]=False
    if memo[num]:
        return memo[num]

    if num!=1 and len(edge[num])==1:
        if num in dic.keys():
            memo[num]=[dic[num],dic[num],dic[num]%2]
            return memo[num]
        else:
            memo[num]=[-float("inf"),float("inf"),2]
        return memo[num]

    ansl=-float("inf")
    ansr=float("inf")
    anseo=2
    if num in dic.keys():
        ansl=dic[num]
        ansr=dic[num]
        anseo=dic[num]%2
    for i in edge[num]:
        if flag[i]:
            l,r,eo=dfs(i)
            if eo!=2:
                eo=(eo+1)%2
            if anseo==2:
                ansr=min(ansr,r+1)
                ansl=max(ansl,l-1)
                anseo=eo
                if ansl>ansr:
                    print("No")
                    exit()
            else:
                ansr=min(ansr,r+1)
                ansl=max(ansl,l-1)
                if ansl>ansr or (eo!=2 and eo!=anseo):
                    print("No")
                    exit()

    memo[num]=[ansl,ansr,anseo]
    return memo[num]

l,r,eo=dfs(1)
print("Yes")
ans={i:-float("inf") for i in range(1,N+1)}
flag={i:True for i in range(2,N+1)}
ans[1]=l
flag[1]=False
q=set([(1,ans[1])])
sub=set([])
while q:
    while q:
        node,num=q.pop()
        for i in edge[node]:
            if flag[i]:
                flag[i]=False
                l,r,eo=memo[i]
                if r>=num-1>=l:
                    ans[i]=num-1
                else:
                    ans[i]=num+1
                sub.add((i,ans[i]))

        if not q:
            q=sub
            sub=set([])
            break

for i in range(1,N+1):
    print(ans[i])

Solution (Python):

"""
Writer: SPD_9X2
https://atcoder.jp/contests/arc063/tasks/arc063_c

数字が置かれている頂点は範囲指定の制約になる
→制約をすべての点に伝播させれば、後はその範囲内から適当に選んで実装すればよい

一度根方向に制約を集め、それを全方位に伝播させればよい？
→それっぽさそう

偶奇に関してはちゃんと考えてね
→条件の両端の偶奇で判断可能
"""

import sys
sys.setrecursionlimit(5*10**5)

N = int(input())

lis = [ [] for i in range(N) ]

for i in range(N-1):

    a,b = map(int,input().split())
    a -= 1
    b -= 1

    lis[a].append(b)
    lis[b].append(a)


l = [float("-inf")] * N
r = [float("inf")]  * N

K = int(input())

for i in range(K):

    V,P = map(int,input().split())
    V -= 1
    l[V] = P
    r[V] = P


def dfs(v,p):

    for nex in lis[v]:

        if nex != p:
            nl,nr = dfs(nex,v)

            if l[v] != float("-inf") and nl != float("-inf") and l[v] % 2 != nl % 2:
                print ("No")
                sys.exit()

            l[v] = max(l[v] , nl)
            r[v] = min(r[v] , nr)

            if l[v] > r[v]:
                print ("No")
                sys.exit()

    return l[v] - 1 , r[v] + 1

dfs(0,0)


from collections import deque
q = deque([0])
unvisit = [True] * N
ans = [None] * N
ans[0] = l[0]

while len(q) > 0:
    
    v = q.popleft()
    unvisit[v] = False

    if l[v] > r[v]:
        print ("No")
        sys.exit()
    
    for nex in lis[v]:

        if unvisit[nex]:

            if l[nex] != float("-inf") and l[v] != float("-inf") and l[v] % 2 == l[nex] % 2:
                print ("No")
                sys.exit()

            l[nex] = max(l[nex] , l[v]-1)
            r[nex] = min(r[nex] , r[v]+1)
            ans[nex] = l[nex]

            q.append(nex)

print ("Yes")
for i in ans:
    print (i)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5+100)
from collections import *

def dfs(v, pv, de):
    for nv in G[v]:
        if nv==pv:
            continue
        
        dfs(nv, v, de+1)
        left[v] = max(left[v], left[nv]-1)
        right[v] = min(right[v], right[nv]+1)
    
    if v in d:
        if d[v]<left[v] or right[v]<d[v] or (d[v]-d[root])%2!=de%2:
            print('No')
            exit()
        else:
            left[v] = d[v]
            right[v] = d[v]
    
def dfs2(v, pv, now):
    ans[v] = now
    
    for nv in G[v]:
        if nv==pv:
            continue
        
        if left[nv]<=now-1<=right[nv]:
            dfs2(nv, v, now-1)
        else:
            dfs2(nv, v, now+1)
    
N = int(input())
G = [[] for _ in range(N)]

for _ in range(N-1):
    A, B = map(int, input().split())
    G[A-1].append(B-1)
    G[B-1].append(A-1)

d = defaultdict(int)
K = int(input())

for _ in range(K):
    V, P = map(int, input().split())
    d[V-1] = P
    root = V-1

left = [-10**18]*N
right = [10**18]*N
dfs(root, -1, 0)
ans = [-1]*N
dfs2(root, -1, d[root])
print('Yes')

for ans_i in ans:
    print(ans_i)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5+100)
from collections import *

def dfs(v, pv, de):
    for nv in G[v]:
        if nv==pv:
            continue
        
        dfs(nv, v, de+1)
        left[v] = max(left[v], left[nv]-1)
        right[v] = min(right[v], right[nv]+1)
    
    if v in d:
        if d[v]<left[v] or right[v]<d[v] or (d[v]-d[root])%2!=de%2:
            print('No')
            exit()
        else:
            left[v] = d[v]
            right[v] = d[v]
    
def dfs2(v, pv, now):
    ans[v] = now
    
    for nv in G[v]:
        if nv==pv:
            continue
        
        if left[nv]<=now-1<=right[nv]:
            dfs2(nv, v, now-1)
        elif left[nv]<=now+1<=right[nv]:
            dfs2(nv, v, now+1)
        else:
            print('No')
            exit()
    
N = int(input())
G = [[] for _ in range(N)]

for _ in range(N-1):
    A, B = map(int, input().split())
    G[A-1].append(B-1)
    G[B-1].append(A-1)

d = defaultdict(int)
K = int(input())

for _ in range(K):
    V, P = map(int, input().split())
    d[V-1] = P
    root = V-1

left = [-10**18]*N
right = [10**18]*N
dfs(root, -1, 0)
ans = [-1]*N
dfs2(root, -1, d[root])
print('Yes')

for ans_i in ans:
    print(ans_i)