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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)
    # print("i = {0}, d[i] = {1} ".format(i, d[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])

Submission status: Runtime Error

Solution code:
import sys


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

Submission status: Runtime Error

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

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 = PV[0]
for v, p in VP:
  P[v] = p
C = [None]*(n+1)
def dfs1(v, par=-1, color=c%2):
  if P[v] == -1:
    l = -float("inf")
    r = float("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 ^ color:
    l += 1
  if r ^ 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 <= 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")

Submission status: Runtime Error

Solution code:

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

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

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

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

import sys

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: Runtime Error

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,None,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 ran[v]
  for x in tr[v]:
    if x == p:
      continue
    ran[x] = 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 ran[v]

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: Runtime Error

Solution code:
import sys

sys.setrecursionlimit = 10**8

n = int(input())
tr = [list() for _ in range(n)]
num = [None]*n
ran = [0]*n
par = [-1]*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,par,dep):
  for x in tr[v]:
    if x == p:
      continue
    par[x] = v
    dep[x] = dep[v] + 1
    dfs(x,v,par,dep)
  return
dfs(root,-1,par,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: Runtime Error

Solution code:
import sys

sys.setrecursionlimit = 10**6

n = int(input())
tr = [list() for _ in range(n)]
num = [None]*n
ran = [0]*n
par = [-1]*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,par,dep):
  for x in tr[v]:
    if x == p:
      continue
    par[x] = v
    dep[x] = dep[v] + 1
    dfs(x,v,par,dep)
  return
dfs(root,-1,par,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: Runtime Error

Solution code:
from collections import deque
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: Runtime Error

Solution code:
from collections import deque
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, 2, 0
    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

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: Runtime Error

Solution code:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const ll INF=1000000010;
const ll MOD=1000000007;
int v[100010],p[100010],lb[100010],ub[100010];
vector<int> G[100010];
bool f=false;
int n;
void dfs(int i,int pre,int l,int r){//(頂点、前の頂点、ありうるmin、ありうるmax)
	if(p[i]!=-1){
		if(p[i]%2!=l%2||p[i]<l||p[i]>r){
			f=true;
			return;
		}
		l=p[i];
		r=p[i];
	}
	lb[i]=l,ub[i]=r;
	for(auto &e:G[i]){
		if(e==pre)continue;
		dfs(e,i,l-1,r+1);
		lb[i]=max(lb[i],lb[e]-1);
		ub[i]=min(ub[i],ub[e]+1);
	}
	for(auto &e:G[i]){
		if(e==pre)continue;
		dfs(e,i,lb[i]-1,ub[i]+1);
	}
}
void dfs2(int i,int pre){
	if(p[i]==-1&&pre!=-1){
		if(lb[i]<=p[pre]+1&&p[pre]+1<=ub[i]){
			p[i]=p[pre]+1;
		}else if(lb[i]<=p[pre]-1&&p[pre]-1<=ub[i]){
			p[i]=p[pre]-1;
		}
	}
	for(auto &e:G[i]){
		if(e==pre)continue;
		dfs2(e,i);
	}
}
int main(){
	cin>>n;
	for(int i=0;i<n-1;i++){
		int a,b;cin>>a>>b;
		G[a].push_back(b);
		G[b].push_back(a);
	}
	int k;cin>>k;
	fill(p,p+n+1,-1);
	for(int i=0;i<k;i++){
		cin>>v[i];
		cin>>p[v[i]];
	}
	dfs(v[0],-1,p[v[0]],p[v[0]]);
	if(f){
		cout<<"No"<<endl;
		return 0;
	}
	cout<<"Yes"<<endl;
	dfs2(v[0],-1);
	for(int i=1;i<=n;i++){
		cout<<p[i]<<endl;
	}
}

Submission status: Runtime Error

Solution code:
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)
    for w in G[v]:
        if p == w:
            continue
        dfs(w, v, x0-1, y0+1)
    memo[v] = x0, y0
    return x0, y0
INF = 10**18
dfs(list(M.keys())[0], -1, -INF, INF)
ok = 1
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: Runtime Error

Solution code:
from scipy.sparse import*
g=[]
n=int(raw_input())
for _ in xrange(n-1):
	a,b=map(int,raw_input().split())
	g+=[(a-1,b-1,1)]
z=[-1]*n
for _ in xrange(int(raw_input())):
	a,b=map(int,raw_input().split())
	g+=[(n,a-1,b)]
	z[a-1]=b
a,b,c=zip(*g)
a=map(int,csgraph.dijkstra(csr_matrix((c,(a,b)),[n+1]*2),0,n))
for i in xrange(n):
	if z[i]>=0 and z[i]!=a[i]:
		print('No')
		sys.exit()
for e in g:
	if e[0]<e[1] and abs(a[e[0]]-a[e[1]])!=1:
		print('No')
		sys.exit()
print('Yes')
print("\n".join(map(str,a[:n])))

Submission status: Runtime Error

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: Runtime Error

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

Submission status: Runtime Error

Solution code:
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
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]:q+=[(c+d,w)]
for i in range(n):
    for w,d in e[i]:
        if abs(cost[i]-cost[w])!=1:print 'No';sys.exit()
print 'Yes'
for i in range(n):print cost[i]

Submission status: Runtime Error

Solution code:
import sys
import heapq
sys.setrecursionlimit(200000)
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
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]:q+=[(c+d,w)]
for i in range(n):
    for w,d in e[i]:
        if abs(cost[i]-cost[w])!=1:print 'No';sys.exit()
print 'Yes'
for i in range(n):print cost[i]

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(200000)
o=lambda:map(int,raw_input().split())
n=int(raw_input())
e=[[] for _ in range(n)]
for _ in range(n-1):
    a,b=o()
    e[a-1]+=[b-1];e[b-1]+=[a-1]
k=int(raw_input())
INF=float('inf')
r=[(-INF,INF)for _ in range(n)]
for _ in range(k):
    v,p=o()
    r[v-1]=(p,p)
vis=[False]*n
def dfs(x):
    vis[x]=True
    r1,r2=r[x]
    for w in e[x]:
        if not vis[w]:
            dfs(w)
            w1,w2=r[w]
            if w1==-INF or r1==-INF or (w1-r1)%2:r1=max(r1,w1-1);r2=min(r2,w2+1)
            else: r1,r2=1,-1
    if r1>r2:r1,r2=1,-1
    return=(r1,r2)
dfs(0)
if r[0]==(1,-1):print 'No';sys.exit()
print 'Yes'
vis=[False]*n
q=[(0,r[0][0])]
ans=[0]*n
while len(q):
    v,c=q.pop(0)
    vis[v]=True
    ans[v]=c
    for w in e[v]:
        if not vis[w]:
            for x in (c+1,c-1):
                if r[w][0]<=x<=r[w][1]:q+=[(w,x)];break
for i in range(n):print int(ans[i])

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(200000)
o=lambda:map(int,raw_input().split())
n=int(raw_input())
e=[[] for _ in range(n)]
for _ in range(n-1):
    a,b=o()
    e[a-1]+=[b-1];e[b-1]+=[a-1]
k=int(raw_input())
INF=float('inf')
r=[(-INF,INF)for _ in range(n)]
for _ in range(k):
    v,p=o()
    r[v-1]=(p,p)
vis=[False]*n
def dfs(x):
    vis[x]=True
    r1,r2=r[x]
    for w in e[x]:
        if not vis[w]:
            dfs(w)
            w1,w2=r[w]
            if w1==-INF or r1==-INF or (w1-r1)%2:r1=max(r1,w1-1);r2=min(r2,w2+1)
            else: r1,r2=1,-1
    return=(r1,r2)
dfs(0)
if r[0]==(1,-1):print 'No';sys.exit()
print 'Yes'
vis=[False]*n
q=[(0,r[0][0])]
ans=[0]*n
while len(q):
    v,c=q.pop(0)
    vis[v]=True
    ans[v]=c
    for w in e[v]:
        if not vis[w]:
            for x in (c+1,c-1):
                if r[w][0]<=x<=r[w][1]:q+=[(w,x)];break
for i in range(n):print int(ans[i])