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)

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

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

from collections import defaultdict
import queue

INF = float("inf")

#入力受け取り
def getlist():
	return list(map(int, input().split()))

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

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

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

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

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

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

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

#処理内容
def main():
	#入力、前処理
	N = int(input())
	G = Graph()
	for i in range(N - 1):
		a, b = getlist()
		a -= 1; b -= 1
		G.add_edge(a, b); G.add_edge(b, a)
	K = int(input())
	value = [None] * N
	for i in range(K):
		V, P = getlist()
		V -= 1
		value[V] = P

	#BFS 偶奇判定
	BF = BFS(G, V, N)
	dist = BF.dist
	odd_even = [0, 0]
	for i in range(N):
		if value[i] != None:
			if value[i] & 1 == dist[i] & 1:
				odd_even[0] += 1
			else:
				odd_even[1] += 1
	
	#例外処理
	if odd_even[0] * odd_even[1] > 0:
		print("No")
		return

	#DFS前処理
	MAX = [INF] * N
	MIN = [-INF] * N
	for i in range(N):
		v = value[i] 
		if v != None:
			MAX[i] = v
			MIN[i] = v
	visit = ["No"] * N
	visit[V] = "Yes"
	#DFS、判定
	DFS(G, MAX, MIN, visit, value, V)
	judge = "Yes"
	for i in range(N):
		if MAX[i] < MIN[i]:
			judge = "No"
			break
	if judge == "No":
		print(judge)
		return

	# value埋めのBFS
	BF2 = BFS2(G, V, N, value, MAX)
	# print(value)
	print("Yes")
	for i in value:
		print(i)

if __name__ == '__main__':
	main()

Submission status: Wrong Answer

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

from collections import defaultdict
import queue

INF = float("inf")

#入力受け取り
def getlist():
	return list(map(int, input().split()))

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

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

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

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

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

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

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

#処理内容
def main():
	#入力、前処理
	N = int(input())
	G = Graph()
	for i in range(N - 1):
		a, b = getlist()
		a -= 1; b -= 1
		G.add_edge(a, b)
		G.add_edge(b, a)
	K = int(input())
	value = [None] * N
	for i in range(K):
		V, P = getlist()
		V -= 1
		value[V] = P

	#BFS
	BF = BFS(G, V, N)
	dist = BF.dist
	odd_even = [0, 0]
	for i in range(N):
		if value[i] != None:
			if value[i] & 1 == dist[i] & 1:
				odd_even[0] += 1
			else:
				odd_even[1] += 1
	
	#例外処理
	if odd_even[0] * odd_even[1] > 0:
		print("No")
		return

	#DFS前処理
	MAX = [INF] * N
	MIN = [-INF] * N
	for i in range(N):
		v = value[i] 
		if v != None:
			MAX[i] = v
			MIN[i] = v
	visit = ["No"] * N
	visit[V] = "Yes"
	#DFS
	DFS(G, MAX, MIN, visit, value, V)
	# print(MAX)
	# print(MIN)
	# print(value)
	judge = "Yes"
	for i in range(N):
		if MAX[i] < MIN[i]:
			judge = "No"
			break
	if judge == "No":
		print(judge)
		return

	#INF埋めのBFS
	BF2 = BFS2(G, V, N, value)
	# print(value)
	print("Yes")
	for i in value:
		print(i)

if __name__ == '__main__':
	main()

Submission status: Wrong Answer

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

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

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] == -INF:
            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: Wrong Answer

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] == -INF:
            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]:
                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: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
INF = 10**9
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 = [-1] * 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] != -1:
            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:
            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] % 2:
        print("No")
        exit()
    if number[v] != -1:
        if not l <= number[v] <= r:
            print("No")
            exit()
        min_c[v] = number[v]
        max_c[v] = number[v]
    return

ans = [-1] * n
def build(v, prev):
    if prev == -1:
        for item in range(min_c[v], max_c[v]+1):
            if item % 2 == odd[v]:
                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: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
INF = 10**9
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 = [-1] * 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] != -1:
            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:
            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] % 2:
        print("No")
        exit()
    if number[v] != -1:
        if not l <= number[v] <= r:
            print("No")
            exit()
        min_c[v] = number[v]
        max_c[v] = number[v]
    return
        
dfs(0, -1)
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import heapq


INF = 10 ** 9

def solve(n, g, k, pa, p):

    q = []
    upper = [INF] * n
    for tpl in pa:
        v, pv = tpl
        upper[v] = pv
        heapq.heappush(q, (pv, v))
    while len(q):
        pv, v = heapq.heappop(q)
        for w in g[v]:
            if p[w] != -1:
                continue
            pw = pv + 1
            if pw < upper[w]:
                upper[w] = pw
                heapq.heappush(q, (pw, w))

    q = []
    lower = [INF] * n
    for tpl in pa:
        v, pv = tpl
        lower[v] = -pv
        heapq.heappush(q, (-pv, v))
    while len(q):
        pv, v = heapq.heappop(q)
        for w in g[v]:
            if p[w] != -1:
                continue
            pw = pv + 1
            if pw < lower[w]:
                lower[w] = pw
                heapq.heappush(q, (pw, w))


    for v in range(n):
        if upper[v] < -lower[v]:
            print('No')
            return

    print('Yes')
    for v in range(n):
        print(-lower[v])


def main():
    n = input()
    n = int(n)
    g = [[] for _ in range(n)]
    for _ in range(n - 1):
        a, b = input().split()
        a = int(a) - 1
        b = int(b) - 1
        g[a].append(b)
        g[b].append(a)
    k = input()
    k = int(k)
    p = [-1] * n
    pa = []
    for _ in range(k):
        v, pv = input().split()
        v = int(v) - 1
        pv = int(pv)
        p[v] = pv
        pa.append((v, pv))


    solve(n, g, k, pa, p)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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]
        print(v, c, 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: Wrong Answer

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):
    if v in M:
        x = y = M[v]
    x0, y0 = memo[v]
    x = max(x, x0); y = min(y, y0)
    for w in G[v]:
        if p == w:
            continue
        dfs1(w, v, x-1, y+1)
    memo[v] = x, y

INF = 10**18
f = list(M.keys())[0]
dfs(f, -1, -INF, INF)
dfs1(f, -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: Wrong Answer

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'
print(r or "Yes\n"+"\n".join(map(str,d[:n])))

Submission status: Wrong Answer

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 _:
		print(e)
		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: Wrong Answer

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))
### bla bla bla ###
print('Yes')
print("\n".join(map(str,a[:n])))

Submission status: Wrong Answer

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

Solution code:
def check(u):
    marks[u] = 1
    for v in g[u]:
        if marks[v] == 0:
            low, high = check(v)
            #print('checking %d, got [%s, %s] from child %d'%(u, low, high, v))
            if low == None:
                continue
            if lows[u] == None:
                lows[u] = low
                highs[u] = high
            else:
                lows[u] = max(lows[u], low)
                highs[u] = min(highs[u], high)
                #print('  adjusted: [%s, %s]' % (lows[u], highs[u]))
                if lows[u] > highs[u]:
                    valid[0] = False
    if lows[u] == None:
        return None, None
    return lows[u] - 1, highs[u] + 1

def fill(u, parent_value):
    marks[u] = 2
    x = parent_value + 1
    if highs[u] != None and x > highs[u]:
        x -= 2
    values[u] = x
    for v in g[u]:
        if marks[v] == 1:
            fill(v, x)

n = int(raw_input())
g = [ [] for i in range(n + 1) ]
for i in range(n - 1):
    u, v = map(int, raw_input().split())
    g[u].append(v)
    g[v].append(u)
lows = [ None for i in range(n + 1) ]
highs = [ None for i in range(n + 1) ]
k = int(raw_input()) 
for i in range(k):
    u, x = map(int, raw_input().split())
    lows[u] = highs[u] = x
marks = [ 0 for i in range(n + 1) ]
valid = [ True ]
check(1)
if valid[0]:
    print('Yes')
    values = [ None for i in range(n + 1) ]
    fill(1, 0 if lows[1] == None else lows[1] - 1)
    print('\n'.join(map(str, [ values[u] for u in range(1, n + 1) ])))
else:
    print('No')

Submission status: Wrong Answer

Solution code:
def dfs(s,cnt,now):
    for i in g[now]:
        if used[i] and not visited[i]:
            visited[i]=True
            tmp=set()
            for j in node[now]:
                if abs(j-node[i][0])<=1:
                    tmp.add(j)
            if len(tmp)==0:
                print("No")
                exit()
            node[now]=list(tmp)
        elif not visited[i]:
            visited[i]=True
            node[i].append(node[s][0])
            node[i].append(node[s][0]+cnt)
            node[i].append(node[s][0]-cnt)
            node[i]=list(set(node[i]))
            dfs(s,cnt+1,i)
    return node

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)
node=[[] for _ in xrange(n)]
used=[False]*n
k=int(raw_input())
for i in xrange(k):
    v,p=map(int,raw_input().split())
    node[v-1].append(p)
    used[v-1]=True

visited=[False]*n
for i in xrange(n):
    if used[i]:
        visited[i]=True
        node=dfs(i,1,i)

print("Yes")
for i in xrange(n):
    print(node[i][0])

Submission status: Wrong Answer

Solution code:
import sys

n = int(raw_input())
e = [[] for i in range(n)]

for i in range(n-1):
    s, t = map(int, raw_input().split())
    e[s-1].append(t-1)
    e[t-1].append(s-1)

k = int(raw_input())
p = {}
cand = {}

now = []
for i in range(k):
    s, t = map(int, raw_input().split())
    p[s-1] = t
    cand[s-1] = set([t])
    if i == 0:
        now.append(s-1)

visited = []
q = {}
m = n

while True:
    visited.extend(now)
    if len(now) == 0:
        break
    for v in now:
        q[m] = v
        m -= 1
        next = [w for w in e[v] if w not in visited]
        next1 = [w for w in next if w in p]
        next2 = [w for w in next if w not in p]

        for w in next1:
            cand[v] &= set([p[w]-1, p[w]+1])
        for w in next2:
            cand[w] = set(i-1 for i in cand[v]) | set(i+1 for i in cand[v])
    now = next

for i in cand:
    if len(cand[i]) == 0:
        print 'No'
        sys.exit()

print 'Yes'
answers = {}
for v in q:
    ans = cand[q[v]].pop()
    answers[q[v]] = ans
    for w in e[q[v]]:
        cand[w] &= set([ans-1, ans+1])

for i in answers:
    print answers[i]

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)
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=100000000
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:r1=r1
            elif r1==-INF:r1,r2=w1-1,w2+1
            elif (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
    r[x]=(r1,r2)
dfs(0)
if r[0][0]>r[0][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 ans[i]