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.



Sample input:
5
1 2
3 1
4 3
3 5
2
2 6
5 7


Sample output:
Yes
5
6
6
5
7

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:

"""
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

#dfsで条件を根方向に集める
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)

#bfsで条件を配る
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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
# MOD = 998244353


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')

Submission status: Accepted

Solution code:
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")

Submission status: Accepted

Solution code:
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")

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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:])))

Submission status: Accepted

Solution code:
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

# 各頂点に対して、子側から見て矛盾しない値の区間[min,max]を持つ
rng = [None] * (N+1)

def calc_rng(v=1,parent=None):
    # None : 自由
    # False : 矛盾
    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
        # merge [x,y] and [x1-1,y1+1]
        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:])))

Submission status: Accepted

Solution code:
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)] # is odd
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")

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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])))

Submission status: Accepted

Solution code:
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])))

Submission status: Accepted

Solution code:
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])))

Submission status: Accepted

Solution code:
#!/usr/bin/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])))

Submission status: Accepted

Solution code:
#!/usr/bin/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 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])))