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
sys.setrecursionlimit(200000)
o=lambda:map(int,raw_input().split())
n=int(raw_input())
e=[[] for _ in range(n)]
for _ in range(n-1):
    a,b=o()
    e[a-1]+=[b-1];e[b-1]+=[a-1]
k=int(raw_input())
INF=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]==(1,-1):print 'No';sys.exit()
if r[0]==(-INF,INF):r[0]=(0,0)
print 'Yes'
vis=[False]*n
q=[(0,r[0][0])]
ans=[0]*n
while len(q):
    v,c=q.pop(0)
    vis[v]=True
    ans[v]=c
    for w in e[v]:
        if not vis[w]:
            for x in (c+1,c-1):
                if r[w][0]<=x<=r[w][1]:q+=[(w,x)];break
for i in range(n):print int(ans[i])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(200000)
o=lambda:map(int,raw_input().split())
n=int(raw_input())
e=[[] for _ in range(n)]
for _ in range(n-1):
    a,b=o()
    e[a-1]+=[b-1];e[b-1]+=[a-1]
k=int(raw_input())
INF=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:r[x]=(r1,r2)
    else:r[x]=(1,-1)
dfs(0)
if r[0]==(1,-1):print 'No';sys.exit()
if r[0]==(-INF,INF):r[0]=(0,0)
print 'Yes'
vis=[False]*n
q=[(0,r[0][0])]
ans=[0]*n
while len(q):
    v,c=q.pop(0)
    vis[v]=True
    ans[v]=c
    for w in e[v]:
        if not vis[w]:
            for x in (c+1,c-1):
                if r[w][0]<=x<=r[w][1]:q+=[(w,x)];break
for i in range(n):print int(ans[i])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(200000)
o=lambda:map(int,raw_input().split())
n=int(raw_input())
e=[[] for _ in range(n)]
for _ in range(n-1):
    a,b=o()
    e[a-1]+=[b-1];e[b-1]+=[a-1]
k=int(raw_input())
INF=10000000000
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:r[x]=(r1,r2)
    else:r[x]=(1,-1)
dfs(0)
if r[0]==(1,-1):print 'No';sys.exit()
if r[0]==(-INF,INF):r[0]=(0,0)
print 'Yes'
vis=[False]*n
q=[(0,r[0][0])]
ans=[0]*n
while len(q):
    v,c=q.pop(0)
    vis[v]=True
    ans[v]=c
    for w in e[v]:
        if not vis[w]:
            for x in (c+1,c-1):
                if r[w][0]<=x<=r[w][1]:q+=[(w,x)];break
for i in range(n):print int(ans[i])

Submission status: Wrong Answer

Solution code:
def main():
    N = input()
    edges = [raw_input() for _ in range(N-1)]
    K = input()
    VP = [raw_input() for _ in range(K)]

    VP = [map(int, _.strip().split()) for _ in VP]
    edges = [map(int, _.strip().split()) for _ in edges]
    # print VP
    # print edges
    scores = {}
    for n_idx, value in VP:
        scores[n_idx] = [value]
    pre_defined = scores.keys()
    # print scores
    def check(value, n1, n2):
        if value == (n1 - n2) or value == (n2 - n1):
            return True
        return False

    for idx in pre_defined:
        for n1, n2 in [l for l in edges if idx in l]:
            v = scores[idx][0]
            n = n1 if idx == n2 else n2
            scores[n] = [_ for _ in scores.get(n, []) if check(_, n1, n2)] + [v - 1, v+1]
    for n1, n2 in edges:
        # print n1, n2
        if scores.get(n1) is None and scores.get(n2) is None:
            pass
        else:
            if scores.get(n1) is None:
                for v in scores.get(n2, []):
                    scores[n1] = [_ for _ in scores.get(n1, []) if check(_, n1, n2)] + [v - 1, v+1]
            elif scores.get(n2) is None:
                for v in scores.get(n1, []):
                    scores[n2] = [_ for _ in scores.get(n2, []) if check(_, n1, n2)] + [v - 1, v+1]

        # print scores.get(n1), scores.get(n2) 
        # print "----------"

    # decide step
    adding = []
    for n in range(1, N+1):
        v = scores.get(n, [None])[0]
        adding.append(v)
    if all([_ is not None for _ in adding]):
        print "Yes"
        for a in adding:
            print a
    else:
        print "No"


    # print scores


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
def main():
    N = input()
    edges = [raw_input() for _ in range(N-1)]
    K = input()
    VP = [raw_input() for _ in range(K)]

    VP = [map(int, _.strip().split()) for _ in VP]
    edges = [map(int, _.strip().split()) for _ in edges]
    # print VP
    # print edges
    scores = {}
    for n_idx, value in VP:
        scores[n_idx] = [value]
    pre_defined = scores.keys()
    # print scores
    def check(value, n1, n2):
        if value == (n1 - n2) or value == (n2 - n1):
            return True
        return False

    for n1, n2 in edges:
        # print n1, n2
        if scores.get(n1) is None and scores.get(n2) is None:
            pass
        else:
            if scores.get(n1) is None:
                for v in scores.get(n2, []):
                    scores[n1] = [_ for _ in scores.get(n1, []) if check(_, n1, n2)] + [v - 1, v+1]
            elif scores.get(n2) is None:
                for v in scores.get(n1, []):
                    scores[n2] = [_ for _ in scores.get(n2, []) if check(_, n1, n2)] + [v - 1, v+1]

        # print scores.get(n1), scores.get(n2) 
        # print "----------"

    # decide step
    adding = []
    for n in range(1, N+1):
        v = scores.get(n, [None])[0]
        adding.append(v)
    if all([_ is not None for _ in adding]):
        print "Yes"
        for a in adding:
            print a
    else:
        print "No"


    # print scores


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**10
mod = 10**9 + 7


def f():
    n = int(input())
    d = collections.defaultdict(list)
    for _ in range(n-1):
        a,b = list(map(int, input().split()))
        d[a].append(b)
        d[b].append(a)
    k = int(input())
    mm = [[-inf, inf] for _ in range(n+1)]
    for _ in range(k):
        v,p = list(map(int, input().split()))
        mm[v] = [p,p]

    def g(mi, k, l):
        m = mm[mi]
        if m[0] == m[1]:
            return [m[0]-k, m[1]+k]

        for di in d[mi]:
            if di == l:
                continue
            dm = g(di, k+1, mi)
            if dm[0] > m[0]:
                mm[mi][0] = dm[0]
            if dm[1] < m[1]:
                mm[mi][1] = dm[1]
        return [m[0]-k, m[1]+k]

    for mi in range(1,n+1):
        m = mm[mi]
        if m[1] == inf:
            g(mi,0,-1)
    r = []
    for i in range(1,n+1):
        m = mm[i]
        if m[0] > m[1]:
            print('No')
            return
        for di in d[i]:
            if di > i:
                continue
            if abs(r[di-1] - m[0]) != 1:
                print('No')
                return
        r.append(m[0])
    print('Yes')
    print('\n'.join(map(str, r)))


f()

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**10
mod = 10**9 + 7


def f():
    n = int(input())
    d = collections.defaultdict(list)
    for _ in range(n-1):
        a,b = list(map(int, input().split()))
        d[a].append(b)
        d[b].append(a)
    k = int(input())
    mm = [[-inf, inf] for _ in range(n+1)]
    for _ in range(k):
        v,p = list(map(int, input().split()))
        mm[v] = [p,p]

    def g(mi, k, l):
        m = mm[mi]
        if m[0] == m[1]:
            return [m[0]-k, m[1]+k]

        for di in d[mi]:
            if di == l:
                continue
            dm = g(di, k+1, mi)
            if dm[0] > m[0]:
                mm[mi][0] = dm[0]
            if dm[1] < m[1]:
                mm[mi][1] = dm[1]
        return [m[0]-k, m[1]+k]

    for mi in range(1,n+1):
        m = mm[mi]
        g(mi,0,-1)
    r = []
    for i in range(1,n+1):
        m = mm[i]
        if m[0] > m[1]:
            print('No')
            return
        for di in d[i]:
            if di > i:
                continue
            if abs(r[di-1] - m[0]) != 1:
                print('No')
                return
        r.append(m[0])
    print('Yes')
    print('\n'.join(map(str, r)))


f()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Time Limit Exceeded

Solution code:
import sys

input=sys.stdin.readline
sys.setrecursionlimit(1000000)

N=int(input())
edge={i:[] for i in range(1,N+1)}
for i in range(0,N-1):
    a,b=map(int,input().split())
    edge[a].append(b)
    edge[b].append(a)

K=int(input())
dic={}
for i in range(K):
    v,p=map(int,input().split())
    dic[v]=0
    dic[v]=p

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

    if num!=1 and len(edge[num])==1:
        if num in dic.keys():
            memo[num]=[dic[num],dic[num],dic[num]%2]
            return memo[num]
        else:
            memo[num]=[-float("inf"),float("inf"),2]
        return memo[num]

    ansl=-float("inf")
    ansr=float("inf")
    anseo=2
    if num in dic.keys():
        ansl=dic[num]
        ansr=dic[num]
        anseo=dic[num]%2
    for i in edge[num]:
        if flag[i]:
            l,r,eo=dfs(i)
            if eo!=2:
                eo=(eo+1)%2
            if anseo==2:
                ansr=min(ansr,r+1)
                ansl=max(ansl,l-1)
                anseo=eo
                if ansl>ansr:
                    print("No")
                    exit()
            else:
                ansr=min(ansr,r+1)
                ansl=max(ansl,l-1)
                if ansl>ansr or (eo!=2 and eo!=anseo):
                    print("No")
                    exit()

    memo[num]=[ansl,ansr,anseo]
    return memo[num]

l,r,eo=dfs(1)
print("Yes")
ans={i:-float("inf") for i in range(1,N+1)}
flag={i:True for i in range(2,N+1)}
ans[1]=l
flag[1]=False
q=set([(1,ans[1])])
sub=set([])
while q:
    while q:
        node,num=q.pop()
        for i in edge[node]:
            if flag[i]:
                flag[i]=False
                l,r,eo=memo[i]
                if r>=num-1>=l:
                    ans[i]=num-1
                    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: Time Limit Exceeded

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-1>ansr or ansl>r+1:
                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: Time Limit Exceeded

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, node):
	for i in G.graph[node]:
		if visit[i] != "Yes":
			visit[i] = "Yes"
			DFS(G, MAX, MIN, visit, 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, MAX, MIN):
		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)
					MAX[i] = min(MAX[i], MAX[v] + 1)
					MIN[i] = max(MIN[i], MIN[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())
	MAX = [INF] * N; MIN = [-INF] * N
	for i in range(K):
		V, P = getlist()
		V -= 1
		MAX[V] = P
		MIN[V] = P

	#BFS 偶奇判定
	BF = BFS(G, V, N)
	dist = BF.dist
	odd_even = [0, 0]
	for i in range(N):
		if MAX[i] != INF:
			if MAX[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
	visit = ["No"] * N
	visit[V] = "Yes"
	DFS(G, MAX, MIN, visit, V)
	#BFS
	BF2 = BFS2(G, V, N, MAX, MIN)

	#判定
	judge = "Yes"
	for i in range(N):
		if MAX[i] < MIN[i]:
			judge = "No"
			break
	if judge == "No":
		print(judge)
		return

	print("Yes")
	for i in MAX:
		print(i)

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

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, node):
	for i in G.graph[node]:
		if visit[i] != "Yes":
			visit[i] = "Yes"
			DFS(G, MAX, MIN, visit, 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, MAX, MIN):
		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)
					MAX[i] = min(MAX[i], MAX[v] + 1)
					MIN[i] = max(MIN[i], MIN[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())
	MAX = [INF] * N; MIN = [-INF] * N
	for i in range(K):
		V, P = getlist()
		V -= 1
		MAX[V] = P
		MIN[V] = P

	#BFS 偶奇判定
	BF = BFS(G, V, N)
	dist = BF.dist
	odd_even = [0, 0]
	for i in range(N):
		if MAX[i] != INF:
			if MAX[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
	visit = ["No"] * N
	visit[V] = "Yes"
	DFS(G, MAX, MIN, visit, V)
	#BFS
	BF2 = BFS2(G, V, N, MAX, MIN)

	#判定
	judge = "Yes"
	for i in range(N):
		if MAX[i] < MIN[i]:
			judge = "No"
			break
	if judge == "No":
		print(judge)
		return

	print("Yes")
	for i in range(N):
		print(MAX[i])

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

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, MAX, MIN):
		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)
					MAX[i] = min(MAX[i], MAX[v] + 1)
					MIN[i] = max(MIN[i], MIN[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)
	#BFS
	BF2 = BFS2(G, V, N, MAX, MIN)
	# print(MAX)
	# print(MIN)

	#判定
	judge = "Yes"
	for i in range(N):
		if MAX[i] < MIN[i]:
			judge = "No"
			break
	if judge == "No":
		print(judge)
		return

	print("Yes")
	for i in range(N):
		print(MAX[i])

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

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)
    for w in G[v]:
        if p == w:
            continue
        dfs(w, v, x0-1, y0+1)
    memo[v] = x0, y0
    return x0, y0
INF = 10**18
dfs(list(M.keys())[0], -1, -INF, INF)
ok = 1
for i in range(N):
    x, y = memo[i]
    if not x <= y:
        ok = 0
if ok:
    print('Yes')
    print(*map(lambda x: x[1], memo), sep='\n')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
import sys
from scipy.sparse import*
g=[]
n=int(sys.stdin.readline())
for _ in xrange(n-1):
	a,b=map(int,sys.stdin.readline().split())
	g.append((a-1,b-1,1))
z=[-1]*n
for _ in xrange(int(sys.stdin.readline())):
	a,b=map(int,sys.stdin.readline().split())
	g.append((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),0,n))
for i in xrange(n):
	if z[i]>=0 and z[i]!=a[i]:
		print('No')
		exit()
for e in g:
	if e[0]<e[1] and abs(a[e[0]]-a[e[1]])!=1:
		print('No')
		exit()
print('Yes')
print("\n".join(map(str,a[:n])))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
import sys
from scipy.sparse import*
g=[]
n=int(sys.stdin.readline())
for _ in xrange(n-1):
	a,b=map(int,sys.stdin.readline().split())
	g.append((a-1,b-1,1))
z=[-1]*n
for _ in xrange(int(sys.stdin.readline())):
	a,b=map(int,sys.stdin.readline().split())
	g.append((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),0,n))
for i in xrange(n):
	if z[i]>=0 and z[i]!=a[i]:
		print('No')
		exit()
for e in g:
	if e[0]<e[1] and abs(a[e[0]]-a[e[1]])!=1:
		print('No')
		exit()
print('Yes')
print("\n".join(map(str,a[:n])))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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