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
input = lambda: sys.stdin.readline().rstrip()

from collections import deque
N = int(input())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

Y = [(-10**9, 10**9) for _ in range(N)]
K = int(input())
for _ in range(K):
    v, p = map(int, input().split())
    Y[v-1] = (p, p)

P = [-1] * N
Q = deque([0])
R = []
while Q:
    i = deque.popleft(Q)
    R.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)


def calc():
    for i in R[::-1]:
        e, o = 0, 0
        l, r = Y[i]
        if r != 10 ** 9:
            if l % 2:
                o = 1
            else:
                e = 1
        for j in X[i]:
            a, b = Y[j]
            if b == 10**9: continue
            if a % 2:
                e = 1
            else:
                o = 1
            l = max(l, a - 1)
            r = min(r, b + 1)
        if (e and o) or (l > r):
            print("No")
            return 0
        elif e or o:
            Y[i] = (l, r)
    
    for i in R[1:]:
        if Y[P[i]][0] - 1 >= Y[i][0]:
            Y[i] = (Y[P[i]][0] - 1, 0)
        else:
            Y[i] = (Y[P[i]][0] + 1, 0)
    
    print("Yes")
    for i in range(N):
        print(Y[i][0])

calc()

Solution (Python):
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7



N = int(sys.stdin.buffer.readline())
AB = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N - 1)]
K = int(sys.stdin.buffer.readline())
VP = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(K)]

graph = [[] for _ in range(N)]
for a, b in AB:
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

mins = [-INF] * N
maxes = [INF] * N
for v, p in VP:
    v -= 1
    mins[v] = p
    maxes[v] = p

root = VP[0][0] - 1


def dfs(v, p=None, p_max=INF, p_min=-INF):
    p_max = min(p_max + 1, maxes[v])
    p_min = max(p_min - 1, mins[v])
    c_max = maxes[v]
    c_min = mins[v]
    for u in graph[v]:
        if u == p:
            continue
        ma, mi = dfs(u, v, p_max, p_min)
        c_max = min(c_max, ma + 1)
        c_min = max(c_min, mi - 1)
    maxes[v] = min(p_max, c_max)
    mins[v] = max(p_min, c_min)
    return c_max, c_min


dfs(root)

ok = True
for ma, mi in zip(maxes, mins):
    ok &= ma >= mi
if not ok:
    print('No')
    exit()

ans = [None] * N
ans[root] = maxes[root]
stack = [(root, None)]

while stack:
    v, p = stack.pop()
    a = ans[v]
    for u in graph[v]:
        if u == p:
            continue
        if mins[u] <= a - 1 <= maxes[u]:
            ans[u] = a - 1
        elif mins[u] <= a + 1 <= maxes[u]:
            ans[u] = a + 1
        else:
            print('No')
            exit()
        stack.append((u, v))
print('Yes')
print(*ans, sep='\n')

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
INF = 10**7
def input():
	return sys.stdin.buffer.readline()[:-1]

n = int(input())
ver = [[-INF, INF] for _ in range(n)]
adj = [[] for _ in range(n)]
for i in range(n-1):
	a, b = map(int, input().split())
	adj[a-1].append(b-1)
	adj[b-1].append(a-1)

k = int(input())
for _ in range(k):
	w, p = map(int, input().split())
	ver[w-1] = [p, p]
	root = w-1

def dfs1(x, parent, bit):
	for v in adj[x]:
		if v == parent:
			continue
		else:
			if ver[v][1] != INF and ver[v][1]%2 == bit:
				print("No")
				sys.exit()
			dfs1(v, x, 1^bit)

dfs1(root, -1, ver[root][1]%2)

def dfs2(x, p):
	if p != -1 and len(adj[x]) == 1:
		return ver[x]
	else:
		for v in adj[x]:
			if v == p:
				continue
			else:
				m, M = dfs2(v, x)
				ver[x][0] = max(ver[x][0], m-1)
				ver[x][1] = min(ver[x][1], M+1)

		if ver[x][0] > ver[x][1]:
			print("No")
			sys.exit()
		else:
			return ver[x]

dfs2(root, -1)

ans = [INF for _ in range(n)]
ans[root] = ver[root][0]

def dfs3(x, p):
	for v in adj[x]:
		if v == p:
			continue
		else:
			if ver[v][0] <= ans[x]-1 <= ver[v][1]:
				ans[v] = ans[x] - 1
			else:
				ans[v] = ans[x] + 1
			dfs3(v, x)
	return

dfs3(root, -1)
print("Yes")
print(*ans, sep="\n")

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

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

NUM = [-1]*N
K = int(input())
for _ in range(K):
    a, b = map(int, input().split())
    NUM[a-1] = b
    root = a-1

MIN = [None]*N
MAX = [None]*N

rootnum = NUM[root]
checked = [False]*N
def dfs(p, d):
    checked[p] = True
    minnum, maxnum = rootnum-d, rootnum+d
    ok = True
    for np in graph[p]:
        if not checked[np]:
            ok = dfs(np, d+1) and ok
            if MIN[np]%2 == minnum%2 or MAX[np]%2 == minnum%2:
                ok = False
            minnum = max(minnum, MIN[np]-1)
            maxnum = min(maxnum, MAX[np]+1)
    if maxnum < minnum:
        ok = False
    if NUM[p] != -1:
        if not (minnum <= NUM[p] <= maxnum):
            ok = False
        MAX[p] = NUM[p]
        MIN[p] = NUM[p]
    else:
        MAX[p] = maxnum
        MIN[p] = minnum
    return ok

if not dfs(root, 0):
    print("No")
else:
    print("Yes")
    checked = [False]*N
    q = [root]
    while q:
        qq = []
        for p in q:
            pnum = NUM[p]
            for np in graph[p]:
                if not checked[np]:
                    if NUM[np] == -1:
                        if MIN[np] <= pnum+1 <= MAX[np]:
                            NUM[np] = pnum+1
                        else:
                            NUM[np] = pnum-1
                    qq.append(np)
                    checked[np] = True
        q = qq
    
    print(*NUM, sep="\n")

Solution (Python):

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

from collections import defaultdict
import queue

INF = float("inf")


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

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

	def get_nodes(self):
		return self.graph.keys()

class BFS(object):
	def __init__(self, graph, s, N):
		self.g = graph.graph
		self.Q = queue.Queue()
		self.Q.put(s)
		self.dist = [INF] * N
		self.dist[s] = 0
		self.visit = ["No"] * N
		self.visit[s] = "Yes"
		while not self.Q.empty():
			v = self.Q.get()
			for i in self.g[v]:
				if self.visit[i] == "No":
					self.dist[i] = self.dist[v] + 1
					self.Q.put(i)
					self.visit[i] = "Yes"

def DFS(G, MAX, MIN, visit, node):
	for i in G.graph[node]:
		if visit[i] != "Yes":
			visit[i] = "Yes"
			DFS(G, MAX, MIN, visit, i)
			MAX[node] = min(MAX[node], MAX[i] + 1)
			MIN[node] = max(MIN[node], MIN[i] - 1)

class BFS2(object):
	def __init__(self, graph, s, N, MAX, MIN):
		self.g = graph.graph
		self.Q = queue.Queue()
		self.Q.put(s)
		self.visit = ["No"] * N
		self.visit[s] = "Yes"
		while not self.Q.empty():
			v = self.Q.get()
			for i in self.g[v]:
				if self.visit[i] == "No":
					self.visit[i] = "Yes"
					self.Q.put(i)
					MAX[i] = min(MAX[i], MAX[v] + 1)
					MIN[i] = max(MIN[i], MIN[v] - 1)


def main():
	
	N = int(input())
	G = Graph()
	for i in range(N - 1):
		a, b = getlist()
		a -= 1; b -= 1
		G.add_edge(a, b); G.add_edge(b, a)
	K = int(input())
	MAX = [INF] * N; MIN = [-INF] * N
	for i in range(K):
		V, P = getlist()
		V -= 1
		MAX[V] = P
		MIN[V] = P

	
	BF = BFS(G, V, N)
	dist = BF.dist
	odd_even = [0, 0]
	for i in range(N):
		if MAX[i] != INF:
			if MAX[i] & 1 == dist[i] & 1:
				odd_even[0] += 1
			else:
				odd_even[1] += 1
	
	
	if odd_even[0] * odd_even[1] > 0:
		print("No")
		return

	
	visit = ["No"] * N
	visit[V] = "Yes"
	DFS(G, MAX, MIN, visit, V)
	
	BF2 = BFS2(G, V, N, MAX, MIN)

	
	judge = "Yes"
	for i in range(N):
		if MAX[i] < MIN[i]:
			judge = "No"
			break
	if judge == "No":
		print(judge)
		return

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

if __name__ == '__main__':
	main()

Solution (Python):
import sys
readline = sys.stdin.readline   

def getpar(Edge, p):
    N = len(Edge)
    par = [0]*N
    par[0] = -1
    par[p]  -1
    stack = [p]
    visited = set([p])
    while stack:
        vn = stack.pop()
        for vf in Edge[vn]:
            if vf in visited:
                continue
            visited.add(vf)
            par[vf] = vn
            stack.append(vf)
    return par

def topological_sort_tree(E, r):
    Q = [r]
    L = []
    visited = set([r])
    while Q:
        vn = Q.pop()
        L.append(vn)
        for vf in E[vn]:
            if vf not in visited:
                visited.add(vf)
                Q.append(vf)
    return L

def getcld(p):
    res = [[] for _ in range(len(p))]
    for i, v in enumerate(p[1:], 1):
        res[v].append(i)
    return res


def check(L, Par, wri, even):
    for i in range(len(Par)):
        if wri[i] and (wri[i] % 2 == even[i]):
            return False
    
    inf = 10**9+7
    dpu = [w if w is not None else inf for w in wri]
    dpd = [w if w is not None else -inf for w in wri]
    for l in L[::-1][:-1]:
        if dpu[l] == inf:
            continue
        if dpd[l] > dpu[l]:
            return False
        p = Par[l]
        dpu[p] = min(dpu[p], dpu[l] + 1)
        dpd[p] = max(dpd[p], dpd[l] - 1)
    if dpd[root] > dpu[root]:
        return False
    ans = [None]*N
    ans[root] = wri[root]
    for l in L[1:]:
        p = Par[l]
        if ans[p] - 1 >= dpd[l]:
            ans[l] = ans[p] - 1
        else:
            ans[l] = ans[p] + 1
    return ans
N = int(readline())
Edge = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, readline().split())
    a -= 1
    b -= 1
    Edge[a].append(b)
    Edge[b].append(a)
K = int(readline())

VP = [tuple(map(lambda x: int(x), readline().split())) for _ in range(K)]
wri = [None]*N
for v, p in VP:
    wri[v-1] = p

root = VP[0][0] - 1
Par = getpar(Edge, root)
L = topological_sort_tree(Edge, root)

even = [True]*N
even[root] = (wri[root] %2 == 0)
for l in L[1:]:
    p = Par[l]
    even[l] = not even[p]
ans = check(L, Par, wri, even)
if ans == False:
    print('No')
else:
    print('Yes')
    print('\n'.join(map(str, ans)))

Solution (Python):
import sys

sys.setrecursionlimit(10**6)

n = int(input())
tr = [list() for _ in range(n)]
num = [None]*n
ran = [0]*n
dep = [0]*n
for _ in range(n-1):
  a,b = map(int,input().split())
  a -= 1; b -= 1
  tr[a].append(b)
  tr[b].append(a)
k = int(input())
root,c = map(int,input().split())
root -= 1
num[root] = c
def dfs(v,p,dep):
  for x in tr[v]:
    if x == p:
      continue
    dep[x] = dep[v] + 1
    dfs(x,v,dep)
  return
dfs(root,-1,dep)
for _ in range(k-1):
  v,c = map(int,input().split())
  v -= 1
  if abs(c-num[root]) > dep[v] or dep[v]%2 != (c-num[root])%2:
    print("No")
    exit(0)
  num[v] = c

def dfs2(v,p,ran):
  cur = [-10**9,10**9] if num[v] is None else [num[v],num[v]]
  if tr[v] == [p]: 
    ran[v] = tuple(cur)
    return
  for x in tr[v]:
    if x == p:
      continue
    dfs2(x,v,ran)
    if ran[x][0] > cur[0]:
      cur[0] = ran[x][0]
    if ran[x][1] < cur[1]:
      cur[1] = ran[x][1]
  cur[0] -= 1; cur[1] += 1
  ran[v] = tuple(cur)
  return

dfs2(root,None,ran)
  
q = [(root,None)]
while q:
  v,p = q.pop()
  for x in tr[v]:
    if x == p:
      continue
    if ran[x][0]<=num[v]+1<=ran[x][1]:
      num[x] = num[v] + 1
    elif ran[x][0]<=num[v]-1<=ran[x][1]:
      num[x] = num[v] - 1
    else:
      print("No")
      exit(0)
    q.append((x,v))
print("Yes")
for c in num:
  print(c)

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
INF = 10**7
n = int(input())
edge = [[] for _ in range(n)]
for i in range(n - 1):
    u, v = [int(item) - 1 for item in input().split()]
    edge[u].append(v)
    edge[v].append(u)
k = int(input())
number = [-INF] * n
for i in range(k):
    v, c = [int(item) for item in input().split()]
    number[v - 1] = c

min_c = [-INF] * n
max_c = [INF] * n
odd = [-1] * n

def dfs(v, prev):
    if len(edge[v]) == 1 and prev is not -1:
        if number[v] != -INF:
            min_c[v] = number[v]
            max_c[v] = number[v]
            odd[v] = number[v] % 2
        return
    l = -INF; r = INF
    for item in edge[v]:
        if item == prev:
            continue
        dfs(item, v)
        if odd[v] == -1 and odd[item] != -1:
            odd[v] = (odd[item] + 1) % 2
        l = max(l, min_c[item] - 1)
        r = min(r, max_c[item] + 1)
        if odd[item] is not -1 and odd[v] == odd[item]:
            print("No")
            exit()
    min_c[v] = l
    max_c[v] = r
    if l > r:
        print("No")
        exit()
    if r == l and r % 2 != odd[v]:
        print("No")
        exit()
    if number[v] != -INF:
        if not l <= number[v] <= r:
            print("No")
            exit()
        min_c[v] = number[v]
        max_c[v] = number[v]
        odd[v] = number[v] % 2
    return

ans = [-INF] * n
def build(v, prev):
    if prev == -1:
        for item in range(min_c[v], max_c[v]+1):
            if item % 2 == odd[v] or odd[v] == -1:
                ans[v] = item
                break
    else:
        if min_c[v] <= ans[prev] + 1 <= max_c[v]:
            ans[v] = ans[prev] + 1
        else:
            ans[v] = ans[prev] - 1
    for item in edge[v]:
        if item == prev:
            continue
        build(item, v)
    return
        
dfs(0, -1)
print("Yes")        
build(0, -1)
for item in ans:
    print(item)

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline

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


def check(par, chi):
    par_min, par_max = ans[par]
    chi_min, chi_max = ans[chi]
    if (par_min - chi_min) % 2 == 0:
        print('No')
        sys.exit()
    if par_min - 1 > chi_max or par_max + 1 < chi_min:
        print('No')
        sys.exit()
    ans[chi] = [max(par_min - 1, chi_min), min(par_max + 1, chi_max)]


que = deque()
que.append(V)
seen = [0] * (N + 1)
parent = [0] * (N + 1)
v_list = []
while que:
    v = que.pop()
    seen[v] = 1
    v_list.append(v)
    for u in adj[v]:
        if seen[u] == 0:
            parent[u] = v
            check(v, u)
            que.append(u)

v_list.reverse()
for v in v_list[:-1]:
    u = parent[v]
    check(v, u)

que = deque()
que.append(V)
seen = [0] * (N + 1)
while que:
    v = que.pop()
    seen[v] = 1
    for u in adj[v]:
        if seen[u] == 0:
            check(v, u)
            que.append(u)

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

Solution (Python):
import sys
sys.setrecursionlimit(500000)

N = int(input())
E = [[] for _ in range(N+1)]
for _ in range(N-1):
    a, b = map(int, input().split())
    E[a].append(b)
    E[b].append(a)
K = int(input())
L = [-float("inf")] * (N+1)
R = [float("inf")] * (N+1)
for _ in range(K):
    v, p = map(int, input().split())
    L[v] = p
    R[v] = p

tour = []
def dfs(v, p):
    tour.append(v)
    for u in E[v]:
        if u!=p:
            dfs(u, v)
            tour.append(v)
dfs(v, 0)

l, r = L[v], R[v]
odd = p % 2
for v in tour[1:]:
    l -= 1
    r += 1
    odd = 1 - odd
    l_, r_ = L[v], R[v]
    if r_ != float("inf") and r_%2 != odd:
        print("No")
        exit()
    l = max(l, l_)
    r = min(r, r_)
    L[v] = l
    R[v] = r
for v in tour[-2::-1]:
    l -= 1
    r += 1
    odd = 1 - odd
    l_, r_ = L[v], R[v]
    l = max(l, l_)
    r = min(r, r_)
    if l > r:
        print("No")
        exit()
    L[v] = l
    R[v] = r
Ans = [-1] * (N+1)
print("Yes")
print("\n".join(map(str, L[1:])))

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

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

K = int(input())
v_to_p = [None] * (N+1)
for _ in range(K):
    v,p = map(int,input().split())
    v_to_p[v] = p


rng = [None] * (N+1)

def calc_rng(v=1,parent=None):
    
    
    x = v_to_p[v]
    y = x
    for c in graph[v]:
        if c == parent:
            continue
        ret = calc_rng(c,v)
        if ret == False:
            return False
        x1,y1 = ret
        if x1 is None:
            continue
        
        if x is None:
            x,y = x1-1, y1+1
            continue
        
        if not (x - x1) & 1:
            return False
        if x < x1 - 1:
            x = x1 - 1
        if y > y1 + 1:
            y = y1 + 1
    if x is not None and x > y:
        return False
    rng[v] = (x,y)
    return x,y

def set_value(v=1, parent=None):
    if v_to_p[v] is None:
        p = v_to_p[parent]
        x,y = rng[v]
        if x is None:
            v_to_p[v] = p + 1
        else:
            if x <= p+1 <= y:
                v_to_p[v] = p+1
            else:
                v_to_p[v] = p-1
    for c in graph[v]:
        if c == parent:
            continue
        set_value(c,v)

ret = calc_rng()
if ret == False:
    print('No')
else:
    v_to_p[1] = rng[1][0]
    set_value()
    print('Yes')
    print('\n'.join(map(str,v_to_p[1:])))

Solution (Python):
from collections import deque
import sys
sys.setrecursionlimit(int(1e7))

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

N = int(input())
G = [[] for _ in range(N+1)]

X = [-1 for _ in range(N+1)] 
U = [1e7 for _ in range(N+1)]
L = [-1e7 for _ in range(N+1)]

for _ in range(N-1):
    a, b = inpl()
    G[a].append(b)
    G[b].append(a)

K = int(input())
for _ in range(K):
    v, p = inpl()
    U[v], L[v], X[v] = p, p, p%2

searched = [0]*(N+1)

def dfs(u, l, x, i):
    searched[i] = True
    if X[i] >= 0 and X[i] != x:
        X[i] = 2
        return -1e7, 1e7
    U[i] = min(U[i], u)
    L[i] = max(L[i], l)
    X[i] = x

    for j in G[i]:
        if searched[j]:
            continue
        nu, nl = dfs(U[i]+1, L[i]-1, (X[i]+1)%2, j)
        U[i] = min(U[i], nu+1)
        L[i] = max(L[i], nl-1)
    return U[i], L[i]

dfs(U[v], L[v], X[v], v)

Q = [v]
searched = [0]*(N+1)
answer = [0]*(N+1)
answer[v] = U[v] 
OK = True

if max(X) == 2:
    OK = False
    Q = []

while Q:
    p = Q.pop()
    for q in G[p]:
        if searched[q]:
            continue
        searched[q] = True
        Q.append(q)
        if L[q] <= answer[p] + 1 <= U[q]:
            answer[q] = answer[p] + 1
        elif L[q] <= answer[p] - 1 <= U[q]:
            answer[q] = answer[p] - 1
        else:
            OK = False
            Q = []
            break
if OK:
    print("Yes")
    print(*answer[1:], sep="\n")
else:
    print("No")

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
N = int(input())
G = [[] for i in range(N)]
for i in range(N-1):
    A, B = map(int, input().split())
    G[A-1].append(B-1)
    G[B-1].append(A-1)
M = {}
K = int(input())
for i in range(K):
    V, P = map(int, input().split())
    M[V-1] = P
memo = [0]*N
def dfs(v, p, x, y):
    if v in M:
        x = y = M[v]
    x0 = x; y0 = y
    for w in G[v]:
        if p == w:
            continue
        s, t = dfs(w, v, x-1, y+1)
        x0 = max(x0, s-1); y0 = min(y0, t+1)
    memo[v] = x0, y0
    return x0, y0
def dfs1(v, p, x, y, c):
    if v in M:
        x = y = M[v]
        if c != (M[v] % 2):
            return 0
    x0, y0 = memo[v]
    x = max(x, x0); y = min(y, y0)
    for w in G[v]:
        if p == w:
            continue
        if not dfs1(w, v, x-1, y+1, c^1):
            return 0
    memo[v] = x, y
    return 1

INF = 10**18
f = list(M.keys())[0]
dfs(f, -1, -INF, INF)
ok = dfs1(f, -1, -INF, INF, M[f]%2)
for i in range(N):
    x, y = memo[i]
    if not x <= y:
        ok = 0
if ok:
    print('Yes')
    print(*map(lambda x: x[1], memo), sep='\n')
else:
    print('No')

Solution (Python):
from heapq import heappush, heappop

def checker():
  N=int(raw_input())
  edge=[[] for _ in xrange(N)]
  for _ in xrange(N-1):
    a,b=map(int,raw_input().split())
    edge[a-1]+=[b-1]
    edge[b-1]+=[a-1]
  P=[None]*N
  d=[False]*N
  q=[]
  K=int(raw_input())
  for _ in xrange(K):
    v,p=map(int,raw_input().split())
    P[v-1]=p
    d[v-1]=True
    heappush(q, (p, v-1))
  while q:
    p,v=heappop(q)
    for z in edge[v]:
      if P[z] is None:
        if not d[z]:
          P[z]=p+1
          d[z]=True
          heappush(q, (p+1, z))
      else:
        if P[z] not in (p-1, p+1):
          print "No"
          return
        if not d[z]:
          d[z]=True
          heappush(q, (f[z], z))
  print "Yes"
  for i in P: print i

checker()

Solution (Python):
from heapq import*
R=range;I=lambda:map(int,input().split());n=int(input());g=[[]for _ in R(n+1)];z=[-1]*n;d=[1e9]*n+[0];q=[-1]*(n+1);r='';Q=[];heappush(Q,(0,-2,n))
for _ in R(n-1):a,b=I();a-=1;b-=1;g[a]+=[(1,a,b)];g[b]+=[(1,b,a)]
for _ in R(*I()):a,b=I();a-=1;g[n]+=[(b,n,a)];z[a]=b
while Q:
	e=heappop(Q)
	if q[e[2]]!=-1:continue
	q[e[2]]=e[1]
	for f in g[e[2]]:
		if d[f[2]]>e[0]+f[0]:d[f[2]]=e[0]+f[0];heappush(Q,(e[0]+f[0],f[1],f[2]))
for _ in g:
	if any(n!=e[1]and abs(d[e[1]]-d[e[2]])!=1 for e in _):r="No"
if any(~z[i]and z[i]!=d[i]for i in R(n)):r="No"
print(r or"Yes\n"+"\n".join(map(str,d[:n])))

Solution (Python):
import heapq
f=lambda:map(int,input().split());n=int(input());g=[[]for _ in range(n+1)];z=[-1]*n;d=[1e9]*n+[0];q=[-1]*(n+1);r='';Q=[];heapq.heappush(Q,(0,-2,n))
for _ in range(n-1):a,b=f();a-=1;b-=1;g[a]+=[(1,a,b)];g[b]+=[(1,b,a)]
for _ in range(int(input())):a,b=f();a-=1;g[n]+=[(b,n,a)];z[a]=b
while Q:
	e=heapq.heappop(Q)
	if q[e[2]]!=-1:continue
	q[e[2]]=e[1]
	for f in g[e[2]]:
		if d[f[2]]>e[0]+f[0]:d[f[2]]=e[0]+f[0];heapq.heappush(Q,(e[0]+f[0],f[1],f[2]))
for _ in g:
	if any(e[1]!=n and abs(d[e[1]]-d[e[2]])!=1 for e in _):r='No'
if any(z[i]>=0 and z[i]!=d[i] for i in range(n)):r='No'
print(r or "Yes\n"+"\n".join(map(str,d[:n])))

Solution (Python):
import heapq
f=lambda:map(int,input().split());n=int(input());g=[[]for _ in range(n+1)];z=[-1]*n;d=[1e9]*n+[0];q=[-1]*(n+1);r='';Q=[];heapq.heappush(Q,(0,-2,n))
for _ in range(n-1):a,b=f();a-=1;b-=1;g[a]+=[(1,a,b)];g[b]+=[(1,b,a)]
for _ in range(int(input())):a,b=f();a-=1;g[n]+=[(b,n,a)];z[a]=b
while Q:
	e=heapq.heappop(Q)
	if q[e[2]]!=-1:continue
	q[e[2]]=e[1]
	for f in g[e[2]]:
		if d[f[2]]>e[0]+f[0]:d[f[2]]=e[0]+f[0];heapq.heappush(Q,(e[0]+f[0],f[1],f[2]))
for _ in g:
	if any(e[1]!=n and abs(d[e[1]]-d[e[2]])!=1 for e in _):r='No'
else:
	if any(z[i]>=0 and z[i]!=d[i] for i in range(n)):r='No'
print(r or "Yes\n"+"\n".join(map(str,d[:n])))

Solution (Python):

def shortestPath(g,s,dist,prev):
	n = len(g)-1
	Q=[]
	heapq.heappush(Q,(0,-2,s))
	while Q:
		e = heapq.heappop(Q)
		if prev[e[2]]!=-1: continue
		prev[e[2]] = e[1]
		for f in g[e[2]]:
			if dist[f[2]] > e[0] + f[0]:
				dist[f[2]] = e[0] + f[0]
				heapq.heappush(Q,(e[0]+f[0],f[1],f[2]))

import sys,heapq
if sys.version_info[0]>=3:raw_input=input

n=int(raw_input())
g=[[] for _ in range(n+1)]
for _ in range(n-1):
	a,b=map(int,raw_input().split())
	g[a-1]+=[(1,a-1,b-1)]
	g[b-1]+=[(1,b-1,a-1)]
z=[-1]*n
for _ in range(int(raw_input())):
	a,b=map(int,raw_input().split())
	g[n]+=[(b,n,a-1)]
	z[a-1]=b
a=[1e9]*n+[0]
shortestPath(g,n,a,[-1]*(n+1))
if any(z[i]>=0 and z[i]!=a[i] for i in range(n)):
		print('No')
		sys.exit()
for _ in g:
	if any(e[1]!=n and abs(a[e[1]]-a[e[2]])!=1 for e in _):
			print('No')
			sys.exit()
print('Yes')
print("\n".join(map(str,a[:n])))

Solution (Python):

def shortestPath(g,s,dist,prev):
	n = len(g)-1
	Q=[]
	heapq.heappush(Q,(0,-2,s))
	while Q:
		e = heapq.heappop(Q)
		if prev[e[2]]!=-1: continue
		prev[e[2]] = e[1]
		for f in g[e[2]]:
			if dist[f[2]] > e[0] + f[0]:
				dist[f[2]] = e[0] + f[0]
				heapq.heappush(Q,(e[0]+f[0],f[1],f[2]))

import sys,heapq


n=int(raw_input())
g=[[] for _ in range(n+1)]
for _ in xrange(n-1):
	a,b=map(int,raw_input().split())
	g[a-1]+=[(1,a-1,b-1)]
	g[b-1]+=[(1,b-1,a-1)]
z=[-1]*n
for _ in xrange(int(raw_input())):
	a,b=map(int,raw_input().split())
	g[n]+=[(b,n,a-1)]
	z[a-1]=b
a=[1e9]*n+[0]
shortestPath(g,n,a,[-1]*(n+1))
for i in xrange(n):
	if z[i]>=0 and z[i]!=a[i]:
		print('No')
		sys.exit()
for _ in g:
	for e in _:
		if e[1]<e[2] and abs(a[e[1]]-a[e[2]])!=1:
			print('No')
			sys.exit()
print('Yes')
print("\n".join(map(str,a[:n])))

Solution (Python):
import sys
import heapq
o=lambda:map(int,raw_input().split());r=range
n=int(raw_input())
e=[[] for _ in r(n+1)]
for _ in r(n-1):a,b=o();e[a]+=[(b,1)];e[b]+=[(a,1)]
k=int(raw_input())
for _ in r(k):v,p=o();e[v]+=[(0,p)];e[0]+=[(v,p)]
vis=[False]*(n+1)
cst=[10**9]*(n+1)
q=[(0,0)]
heapq.heapify(q)
while len(q):
    c,v=heapq.heappop(q)
    vis[v]=True;cst[v]=c
    for (w,d) in e[v]:
        if not vis[w] and c+d<cst[w]:
            heapq.heappush(q,(c+d,w));cst[w]=c+d
for i in r(n):
    for w,d in e[i+1]:
        if w and abs(cst[i+1]-cst[w])!=1:print'No';sys.exit()
print'Yes'
for i in r(n):print cst[i+1]

Solution (Python):
import sys
import heapq
o=lambda:map(int,raw_input().split())
n=int(raw_input())
e=[[] for _ in range(n+1)]
for _ in range(n-1):a,b=o();e[a]+=[(b,1)];e[b]+=[(a,1)]
k=int(raw_input())
for _ in range(k):v,p=o();e[v]+=[(0,p)];e[0]+=[(v,p)]
vis=[False]*(n+1)
cost=[10**9]*(n+1)
q=[(0,0)]
heapq.heapify(q)
while len(q):
    c,v=heapq.heappop(q)
    vis[v]=True
    cost[v]=c
    for (w,d) in e[v]:
        if not vis[w] and c+d<cost[w]:
            heapq.heappush(q,(c+d,w))
            cost[w]=c+d
for i in range(1,n+1):
    for w,d in e[i]:
        if w!=0 and abs(cost[i]-cost[w])!=1:print 'No';sys.exit()
print 'Yes'
for i in range(n):print cost[i+1]

Solution (Python):
from sys import stdin, stdout
from heapq import heappush, heappop
def main():
    RL = stdin.readline
    n = int(RL())
    e = [[] for _ in xrange(n)]
    for _ in xrange(n - 1):
        x, y = map(int, RL().split())
        x -= 1
        y -= 1
        e[x] += [y]
        e[y] += [x]
    m = int(RL())
    f = [None] * n
    q = []
    d = [None] * n
    for _ in xrange(m):
        x, y = map(int, RL().split())
        x -= 1
        f[x] = y
        d[x] = 1
        heappush(q, (y, x))
    while q:
        y, x = heappop(q)
        for z in e[x]:
            if f[z] is None:
                if d[z] is None:
                    f[z] = y + 1
                    d[z] = 1
                    heappush(q, (y + 1, z))
            else:
                if f[z] not in (y + 1, y - 1):
                    print "No"
                    return
                if d[z] is None:
                    d[z] = 1
                    heappush(q, (f[z], z))
    print "Yes"
    stdout.write('\n'.join(map(str, f)))
    print
main()

Solution (Python):
from sys import exit, setrecursionlimit
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

def read():
  return int(input())

def reads():
  return [int(x) for x in input().split()]

def inc(x):
  if x == "No":
    return "No"
  elif x == "Any":
    return "Any"
  else:
    (a, b, p) = x
    return (a-1, b+1, (p+1)%2)

def imin(x, y):
  if x == "No" or y == "No":
    return "No"
  elif y == "Any":
    return x
  elif x == "Any":
    return y
  else:
    (a1, b1, p1) = x
    (a2, b2, p2) = y
    if p1 != p2 or b1 < a2 or b2 < a1:
      return "No"
    else:
      return (max(a1, a2), min(b1, b2), p1)

setrecursionlimit(1000000)

N = read()

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

for i in range(N-1):
  (A, B) = reads()
  (A, B) = (A-1, B-1)
  edges[A].append(B)
  edges[B].append(A)

K = read()
d = ["Any"] * N

for i in range(K):
  (V, P) = reads()
  V = V - 1
  d[V] = (P, P, P%2)

children = [[] for i in range(N)]
parent = [0] * N

parent[0] = None
def walk(n):
  children[n] = list(edges[n])
  if n != 0:
    children[n].remove(parent[n])
  for i in children[n]:
    parent[i] = n
    walk(i)
    
  d[n] = reduce(imin, (inc(d[i]) for i in children[n]), d[n])

walk(0)

f = [0] * N
def walk2(n, k = None):
  if d[n] == "No":
    print("No"); exit()
  elif d[n] == "Any":
    f[n] = k+1
  else:
    (a, b, p) = d[n]
    if k == None:
      if a % 2 == p:
        f[n] = a
      else:
        f[n] = a + 1
    else:
      if a <= k-1 <= b:
        f[n] = k-1
      elif a <= k+1 <= b:
        f[n] = k+1
      else:
        print("No"); exit()
  for i in children[n]:
    walk2(i, f[n])

walk2(0)

print("Yes")
for i in range(N):
  print(f[i])