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: Wrong Answer

Solution code:
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 <= 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: Wrong Answer

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 = VP[0][0]
for v, p in VP:
  P[v] = p
C = [None]*(n+1)
def dfs1(v, par=-1):
  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)
    l = max(l, nl-1)
    r = min(r, nr+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: Wrong Answer

Solution code:
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] = (max_ret, min_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")

Submission status: Wrong Answer

Solution code:
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(5):
    dep=[-1 for i in range(n+1)]
    dfs(v,0,p,p)
for i,j in zip(mi,ma):
    if i>j:
        print("No")
        break
else:
    print("Yes")
    for i in mi[1:]:
        print(i)

Submission status: Wrong Answer

Solution code:
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
dep=[-1 for i in range(n+1)]
dfs(v,0,p,p)
dep=[-1 for i in range(n+1)]
dfs(v,0,p,p)
for i,j in zip(mi,ma):
    if i>j:
        print("No")
        break
else:
    print("Yes")
    for i in mi[1:]:
        print(i)

Submission status: Wrong Answer

Solution code:
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()
for i in range(k):
    v,p=NM()
    ma[v]=p
    mi[v]=p

dep=[-1 for i in range(n+1)]
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
dfs(v,0,p,p)
dfs(v,0,p,p)
for i,j in zip(mi,ma):
    if i>j:
        print("No")
        break
else:
    print("Yes")
    for i in mi[1:]:
        print(i)

Submission status: Wrong Answer

Solution code:
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()
    #print(dp)
    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][1]==-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(pp)
    print("Yes")
    for p in pp:print(p)

main()

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
print("No")

Submission status: Wrong Answer

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

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

Q = dq([])
for _ in range(K):
  x, v = map(int, input().split())
  ls[x] = v
  rs[x] = v
  Q.append(x)

vis = [0] * (N + 1)
visrev = [0] * (N + 1)
order = []
while len(Q):
  x = Q.popleft()
  order.append(x)
  for y in e[x]:
    ls[y] = max(ls[y], ls[x] - 1)
    rs[y] = min(rs[y], rs[x] + 1)
    if vis[y]: continue
    vis[y] = 1
    Q.append(y)
  for y in re[x]:
    ls[y] = max(ls[y], ls[x] - 1)
    rs[y] = min(rs[y], rs[x] + 1)
    if visrev[y]: continue
    visrev[y] = 1
    Q.append(y)

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

res = [0] * (N + 1)
for x in order[: : -1]:
  res[x] = ls[x]
  for y in e[x]:
    ls[y] = max(ls[y], res[x] - 1)
    rs[y] = min(rs[y], res[x] + 1)
  for y in re[x]:
    ls[y] = max(ls[y], res[x] - 1)
    rs[y] = min(rs[y], res[x] + 1)
  #print(res, ls, rs)
print("Yes")
for r in res[1: ]: print(r)

Submission status: Wrong Answer

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

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

Q = dq([])
for _ in range(K):
  x, v = map(int, input().split())
  ls[x] = v
  rs[x] = v
  Q.append(x)

vis = [0] * (N + 1)
visrev = [0] * (N + 1)
order = []
while len(Q):
  x = Q.popleft()
  order.append(x)
  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 vis[y]: continue
    Q.append(y)
  for y in re[x]:
    ls[y] = max(ls[y], ls[x] - 1)
    rs[y] = min(rs[y], rs[x] + 1)
    if visrev[y]: continue
    Q.append(y)

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

res = [0] * (N + 1)
for x in order[: : -1]:
  res[x] = ls[x]
  for y in e[x]:
    ls[y] = max(ls[y], res[x] - 1)
    rs[y] = min(rs[y], res[x] + 1)
  for y in re[x]:
    ls[y] = max(ls[y], res[x] - 1)
    rs[y] = min(rs[y], res[x] + 1)
  #print(res, ls, rs)
print("Yes")
for r in res[1: ]: print(r)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
from collections import deque as dq
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([])
for _ in range(K):
  x, v = map(int, input().split())
  ls[x] = v
  rs[x] = v
  Q.append(x)

vis = [0] * (N + 1)
order = []
while len(Q):
  x = Q.popleft()
  if vis[x]: continue
  order.append(x)
  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 vis[y]: continue
    Q.append(y)

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

res = [0] * (N + 1)
for x in order[: : -1]:
  res[x] = ls[x]
  for y in e[x]:
    ls[y] = max(ls[y], res[x] - 1)
    rs[y] = min(rs[y], res[x] + 1)
print("Yes")
for r in res[1: ]: print(r)

Submission status: Wrong Answer

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

parent={i:-1 for i in range(1,N+1)}
parent[1]=0
q=set([1])
sub=set([])
while q:
    while q:
        x=q.pop()
        for i in edge[x]:
            if parent[i]==-1:
                parent[i]=x
                sub.add(i)

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


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

    if edge[num]==[parent[num]]:
        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 i!=parent[num]:
            l,r,eo=dfs(i)
            if eo==1:
                eo=0
            elif eo==0:
                eo=1
            if (anseo!=2 and eo!=2 and anseo!=eo) or l>ansr or ansl>r:
                print("No")
                exit()
            else:
                ansr=min(ansr,r+1)
                ansl=max(ansl,l-1)
                if anseo==2:
                    anseo=eo

    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)}
ans[1]=l
q=set([(1,ans[1])])
sub=set([])
while q:
    while q:
        node,num=q.pop()
        for i in edge[node]:
            if i!=parent[node]:
                l,r,eo=memo[i]
                if r>=num-1>=l:
                    ans[i]=num-1
                    sub.add((i,ans[i]))
                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: Wrong Answer

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

parent={i:-1 for i in range(1,N+1)}
parent[1]=0
q=set([1])
sub=set([])
while q:
    while q:
        x=q.pop()
        for i in edge[x]:
            if parent[i]==-1:
                parent[i]=x
                sub.add(i)

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


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

    if edge[num]==[parent[num]]:
        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 i!=parent[num]:
            l,r,eo=dfs(i)
            if eo==1:
                eo=0
            elif eo==0:
                eo=1
            if (anseo!=2 and eo!=2 and anseo!=eo) or l>ansr or ansl>r:
                print("No")
                exit()
            else:
                ansr=min(ansr,r+1)
                ansl=max(ansl,l-1)
                anseo=min(anseo,eo)

    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)}
ans[1]=l
q=set([(1,ans[1])])
sub=set([])
while q:
    while q:
        node,num=q.pop()
        for i in edge[node]:
            if i!=parent[node]:
                l,r,eo=dfs(i)
                if r>=num-1>=l:
                    ans[i]=num-1
                    sub.add((i,ans[i]))
                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: Wrong Answer

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: Wrong Answer

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: Wrong Answer

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: Wrong Answer

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:
                o = 1
            else:
                e = 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: Wrong Answer

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, maxes[v])
    p_min = max(p_min, 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 + 1, p_min - 1)
        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
        else:
            ans[u] = a + 1
        stack.append((u, v))
print('Yes')
print(*ans, sep='\n')

Submission status: Wrong Answer

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

n = int(input())
ver = [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, i))
	adj[b-1].append((a-1, i))

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

edges = [0 for _ in range(n-1)]
tour = []# (どの頂点にいるか，どの辺から来たか)

def dfs(x, p, e):
	global tour
	tour.append((x, e))
	for v, i in adj[x]:
		if v == p:
			continue
		else:
			dfs(v, x, i)

	if x != root:
		tour.append((p, e))

dfs(root, -1, -1)
#print(tour)

def xor(dic, num):
	if num in dic:
		del dic[num]
	else:
		dic[num] = 1

front, back = 0, 1

while back < 2*n-2:
	while ver[tour[back][0]] == INF:
		back += 1

	needed = dict()
	for i in range(front+1, back+1):
		xor(needed, tour[i][1])

	l, gap = len(needed), ver[tour[back][0]] - ver[tour[front][0]]
	if gap > l or gap < -l or gap%2 != l%2:
		print("No")
		sys.exit()
	plus = (gap + l) // 2

	cnt = 0

	for i in range(front+1, back+1):
		x, e = tour[i]
		p = tour[i-1][0]
		if edges[e] != 0:
			if ver[p] - edges[e] != ver[x]:
				print("No")
				sys.exit()
		
		else:	
			if ver[x] < INF:
				if ver[p]+1 != ver[x] and ver[p]-1 != ver[x]:
					print("No")
					sys.exit()
				else:
					edges[e] = ver[x] - ver[p]

			else:
				if e not in needed:
					ver[x] = ver[p] + 1
					edges[e] = 1
				else:
					if cnt < plus:
						ver[x] = ver[p] + 1
						edges[e] = 1
						cnt += 1
					else:
						ver[x] = ver[p] - 1
						edges[e] = -1

	front = back
	back += 1

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

Submission status: Wrong Answer

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

n = int(input())
ver = [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, i))
	adj[b-1].append((a-1, i))

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

edges = [0 for _ in range(n-1)]
tour = []# (どの頂点にいるか，どの辺から来たか)

def dfs(x, p, e):
	global tour
	tour.append((x, e))
	for v, i in adj[x]:
		if v == p:
			continue
		else:
			dfs(v, x, i)

	if x != root:
		tour.append((p, e))

dfs(root, -1, -1)
#print(tour)

def xor(dic, num):
	if num in dic:
		del dic[num]
	else:
		dic[num] = 1

front, back = 0, 1

while back < 2*n-2:
	while ver[tour[back][0]] == INF:
		back += 1

	needed = dict()
	for i in range(front+1, back+1):
		xor(needed, tour[i][1])

	l, gap = len(needed), ver[tour[back][0]] - ver[tour[front][0]]
	if gap > l or gap < -l or gap%2 != l%2:
		print("No")
		sys.exit()
	plus = (gap + l) // 2

	cnt = 0

	for i in range(front+1, back+1):
		x, e = tour[i]
		p = tour[i-1][0]
		if edges[e] != 0:
			if ver[p] - edges[e] != ver[x]:
				print("No")
				sys.exit()
		
		else:	
			if ver[x] < INF:
				if not (ver[p]+1 != ver[x] or ver[p]-1 != ver[x]):
					print("No")
					sys.exit()
				else:
					edges[e] = ver[x] - ver[p]

			else:
				if e not in needed:
					ver[x] = ver[p] + 1
					edges[e] = 1
				else:
					if cnt < plus:
						ver[x] = ver[p] + 1
						edges[e] = 1
						cnt += 1
					else:
						ver[x] = ver[p] - 1
						edges[e] = -1

	front = back
	back += 1

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