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: Time Limit Exceeded

Solution code:
import math

class IntegerTree(object):
	def __init__(self, N):
		self.edges = [[] for i in range(N)]
		self.integers = [float('nan') for i in range(N)]
		self.integer_nodes = {}
		self.done = [False for i in range(N)]

	def make_edge(self, u, v):
		self.edges[u].append(v)
		self.edges[v].append(u)

	def set_integer(self, v, p):
		self.integers[v] = p
		if p in self.integer_nodes:
			self.integer_nodes[p].append(v)
		else:
			self.integer_nodes[p] = [v]

	def check(self, v):
		v_edge = self.edges[v]
		for u in v_edge:
			if math.isnan(self.integers[u]):
				return 0
			if abs(self.integers[v]-self.integers[u])!=1:
				return -1
		return 1

	def argmin_v(self):
		if len(self.integer_nodes.keys())==0:
			return -1
		min_p = min(self.integer_nodes.keys())
		return self.integer_nodes[min_p][0]

	def done_node(self, v):
		self.done[v] = True
		p = self.integers[v]
		self.integer_nodes[p].remove(v)

		if len(self.integer_nodes[p])==0:
			del self.integer_nodes[p]

N = int(input())
A = [0 for i in range(N-1)]
B = [0 for i in range(N-1)]
for i in range(N-1):
	A[i], B[i] = map(lambda x:int(x)-1, input().split())
K = int(input())
V = [0 for i in range(K)]
P = [0 for i in range(K)]
for i in range(K):
	V[i], P[i] = map(int, input().split())
	V[i] = V[i]-1

tree = IntegerTree(N)
for i in range(N-1):
	tree.make_edge(A[i], B[i])
for i in range(K):
	tree.set_integer(V[i], P[i])

fail = False
while True:
	v = tree.argmin_v()
	if v==-1:
		break
	state = tree.check(v)
	if state==-1:
		print("No")
		fail = True
		break
	if state==1:
		tree.done_node(v)
		continue
	if state==0:
		p = tree.integers[v]
		for u in tree.edges[v]:
			if math.isnan(tree.integers[u]):
				tree.set_integer(u, p+1)
	if tree.check(v)==-1:
		print("No")
		fail = True
		break
	else:
		tree.done_node(v)
if not fail:
	print("Yes")
	for i in range(N):
		print(tree.integers[i])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
import sys
#if sys.version_info[0]>=3:raw_input=input

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: Time Limit Exceeded

Solution code:
#!/usr/bin/python
import sys
#if sys.version_info[0]>=3:raw_input=input

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)]
	g+=[(b-1,a-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(coo_matrix((c,(a,b)),[n+1]*2),1,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: Time Limit Exceeded

Solution code:
#!/usr/bin/python
import sys
#if sys.version_info[0]>=3:raw_input=input

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)]
	g+=[(b-1,a-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(csc_matrix((c,(a,b)),[n+1]*2),1,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: Time Limit Exceeded

Solution code:
import sys
#if sys.version_info[0]>=3:raw_input=input

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)]
	g+=[(b-1,a-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),1,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: Time Limit Exceeded

Solution code:
import sys
if sys.version_info[0]>=3:raw_input=input

from scipy.sparse import*
g=[]
n=int(raw_input())
for _ in [0]*~-n:
	a,b=map(int,raw_input().split())
	g+=[[a-1,b-1,1]]
	g+=[[b-1,a-1,1]]
z=[-1]*n
for _ in [0]*int(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),1,n))
for i in range(n):
	if z[i]>=0 and z[i]!=a[i]:
		print('No')
		sys.exit()
	z[i]=a[i]
for e in g:
	if e[0]!=n and abs(z[e[0]]-z[e[1]])!=1:
		print('No')
		sys.exit()
print('Yes')
print("\n".join(map(str,a[:n])))

Submission status: Time Limit Exceeded

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=[0]*(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]:heapq.heappush(q,(c+d,w))
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: Memory Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)

def dfs1(now,par,depth):
    if num[now]!=-1:
        if (num[s]+depth)%2!=num[now]%2:
            print "No"
            exit()
    for nx in g[now]:
        if nx==par:continue
        dfs1(nx,now,depth+1)

def dfs2(now,par):
    l=-10**15
    r=10**15
    for nx in g[now]:
        if nx==par:continue
        tmpl,tmpr=dfs2(nx,now)
        l=max(l,tmpl)
        r=min(r,tmpr)
    if l>r:
        print "No"
        exit()
    if num[now]!=-1:
        if l<=num[now]<=r:
            lr[now]=[num[now],num[now]]
        else:
            print "No"
            exit()
    else:
        lr[now]=[l,r]
    return lr[now][0]-1,lr[now][1]+1

def dfs3(now,par,val):
    l,r=lr[now]
    if l<=val+1<=r:
        num[now]=val+1
        val=val+1
    elif l<=val-1<=r:
        num[now]=val-1
        val=val-1
    for nx in g[now]:
        if nx==par:continue
        dfs3(nx,now,val)


n=int(raw_input())
g=[[] for _ in xrange(n)]
for i in xrange(n-1):
    a,b=map(int,raw_input().split())
    a-=1;b-=1
    g[a].append(b)
    g[b].append(a)
k=int(raw_input())
num=[-1]*n
for i in xrange(k):
    v,p=map(int,raw_input().split())
    v-=1
    num[v]=p
s=v
dfs1(s,-1,0)
lr=[[] for _ in xrange(n)]
lr[s]=[num[s],num[s]]
dfs2(s,s)
dfs3(s,s,num[s])
print "Yes"
for i in xrange(n):
    print num[i]

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)


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


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


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

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

Submission status: Accepted

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

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

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

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

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

dfs1(1, 0)

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

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

Submission status: Accepted

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

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

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

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

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

dfs1(1, 0)

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

dfs2(1, 0)

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

print('Yes')

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

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

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

Submission status: Accepted

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

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

INF = 10**18

import sys
input = sys.stdin.readline

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

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

K = int(input())

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

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

even = []
odd = []

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

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

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

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

Submission status: Accepted

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

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

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


# トポソ, 偶奇チェック
dist = [-1] * N
parent = [-1] * N
dist[root] = 0
order = []
node = [root]
bm = (dist[root] ^ res[root]) & 1
while node:
    s = node.pop()
    order.append(s)
    if res[s] != -1 and bm != (dist[s] ^ res[s]) & 1:
        print("No")
        exit()
    for t in edge[s]:
        if dist[t] != -1:
            continue
        parent[t] = s
        dist[t] = dist[s] + 1
        node.append(t)

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

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

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

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

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

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

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

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

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

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

for v in order[:0:-1]:
    p = parent[v]
    #elif val[v]== INF: # vに好きな数書ける
    h,l = high[v]+1,low[v]-1
    
    if h >= INF:
        pass
    elif high[p]>=INF:
        high[p] = h
        low[p] = l
    elif (high[p]-h)&1==0: #偶奇一致
        if h < high[p]: high[p] = h
        if l > low[p]: low[p] = l
        if high[p] < low[p]:
            print("No")
            break
    else: #偶奇違ってダメ
        print("No")
        break
    #print(v,val,high,low)
    
else: #OK
    print("Yes")
    for v in order:
        if val[v] == INF:
            val[v] = low[v]
        for c in g[v]:
            high[c] = min(high[c],val[v]+1)
            low[c] = max(low[c],val[v]-1)
    
    
    print(*val,sep="\n")

Submission status: Accepted

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 == r:
    A[v] = l
  else:
    if l <= ini-1 <= r:
      A[v] = ini-1
    else:
      A[v] = ini+1
  for nv in T[v]:
    if nv == par:
      continue
    dfs2(nv, A[v], v)
dfs2(r, P[r][0])
print("Yes")
print(*A[1:], sep="\n")

Submission status: Accepted

Solution code:
import heapq
import sys
input = sys.stdin.readline
INF = 10 ** 18


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

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

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

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

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

Submission status: Accepted

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] = (min_ret, max_ret)
    return min_ret, max_ret, u_flg

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

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

Submission status: Accepted

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

Submission status: Accepted

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

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

main()

Submission status: Accepted

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

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

    # まず各頂点の偶奇を計算する
    parity = [-1]*n
    root = vp[0][0]-1
    p = vp[0][1] % 2
    parity[root] = p
    q = [root]
    while q:  # BFS
        p ^= 1
        qq = []
        while q:
            i = q.pop()
            for j in g[i]:
                if parity[j] == -1:
                    parity[j] = p
                    qq.append(j)
        q = qq

    # 偶奇と塗った色があっていなければ即座に終了
    for v, p in vp:
        if p % 2 != parity[v-1]:
            print("No")
            return

    # バックトラック法を行い解の範囲を探索する
    ans_range = [[-10**10, 10**10] for _ in [0]*n]
    q = [root]
    vp = {v-1: p for v, p in vp}
    M = 10**10
    m = -10**10
    g2 = [set(gg) for gg in g]
    while q:
        i = q[-1]
        if i in vp:
            if m <= vp[i] <= M:
                M = vp[i]
                m = M
                ans_range[i] = [m, M]
            else:
                print("No")
                return
        else:
            m2, M2 = ans_range[i]
            if M2 < m or M < m2:
                print("No")
                return
            m = max(m, m2)
            M = min(M, M2)
            ans_range[i] = [m, M]
        if g2[i]:
            j = g2[i].pop()
            g2[j].remove(i)
            q.append(j)
        else:
            q.pop()
        m -= 1
        M += 1

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


main()

Submission status: Accepted

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 ls[y] % 2 == ls[x] % 2:
      print("No")
      exit(0)
    if vis[y]: continue
    Q.append(y)

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


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

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