Problem:


Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq Q \leq 2 \times 10^5

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10

Sample Output 2

20 20 20 20 20 20



Sample input:
4 3
1 2
2 3
2 4
2 10
1 100
3 1


Sample output:
100 110 111 110

Submission status: Runtime Error

Solution code:
class ki:
    value=0
    def __init__(self):
        self.kid=[]

    def add_kid(self,it):
        self.kid.append(it)

    def calc(self,list_k,val=0):
        #print(self.kid)
        self.value+=val
        for i in self.kid:
            list_k[i].calc(list_k,self.value)


N,Q=input().split()
N,Q=int(N),int(Q)
ki_list=[ki()]
for i in range(1,N+1):
    ki_list.append(ki())

for i in range(N-1):
    a,b=input().split()
    ki_list[int(a)].add_kid(int(b))

for i in range(Q):
    p,x=input().split()
    ki_list[int(p)].value+=int(x)

ki_list[1].calc(ki_list)

print(ki_list[1].value ,end="")
for i in ki_list[2:]:
    print(" " + str(i.value),end="")

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())

graph = [[] for i in range(N)]
ans = [ 0 for i 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)

for _ in range(Q):
    p, x = map(int, input().split())
    ans[p-1] = x
    
def dfs(v, p=-1):
    for u in graph[v]:
        if u != p:
            ans[u] += ans[v]
            dfs(u,v)

dfs(0)
print(*ans)

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split(' '))


visit = [0 for _ in range(n)]
point = [0 for _ in range(n)]
dic = [[] for _ in range(n)]

def add_p(num):
    if visit[num] == 1:
        return 0
    visit[num] = 1
    for i in dic[num]:
        if visit[i] == 0:
            point[i] += point[num]
            add_p(i)
    return 0

for _ in range(n-1):
    a, b = map(int, input().split(' '))
    dic[a-1].append(b-1)
    dic[b-1].append(a-1)
for _ in range(q):
    p, x = map(int, input().split(' '))
    point[p-1] += x

add_p(0)

print(*point)

Submission status: Runtime Error

Solution code:
def main():
    n, q = map(int, input().split(' '))
    visit = [0 for _ in range(n)]
    point = [0 for _ in range(n)]
    dic = [[] for _ in range(n)]

    def add_p(num):
        if visit[num] == 1:
            return 0
        visit[num] = 1
        for i in dic[num]:
            if visit[i] == 0:
                point[i] += point[num]
                add_p(i)
        return 0
    for _ in range(n-1):
        a, b = map(int, input().split(' '))
        dic[a-1].append(b-1)
        dic[b-1].append(a-1)
    for _ in range(q):
        p, x = map(int, input().split(' '))
        point[p-1] += x
    add_p(0)
    print(*point)

main()

Submission status: Runtime Error

Solution code:
import sys
import collections


input = sys.stdin.readline
n, qq = list(map(int,input().rstrip().split()))

ls = collections.defaultdict(list)
ls[1]

for i in range(n-1):
    a, b = list(map(int,input().rstrip().split()))
    ls[a].append(b)
    #ls[b].append(a)

ans = [0] * n

for i in range(qq):
    p,x = list(map(int,input().rstrip().split()))
    ans[p-1] += x

q = collections.deque()
q.append(1)
fq = collections.defaultdict(list)
while True:
    if len(q)!=0:
        p = q.popleft()
        fq[p]
        for i in ls[p]:
        if i not in fq:
            q.append(i)
            ans[i-1] += ans[p-1]
    else:
        break


print(*ans)

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())

graph = []
ope = []

for i in range(N-1):
    a, b = map(int, input().split())
    graph.append((a, b))

for i in range(Q):
    p, x=map(int, input().split())
    ope.append((p, x))

def getnext(Num):
    next = set()
    for t in graph:
        if (t[0] == Num):
            next.add(t[1])
            
    return next

result = [0]*(N+1)

for o in ope:
    next.add(o[0])
    score = o[1]
    
    while next:
        n = next.pop()
        result[n] += score
        next |= getnext(n)

for i in result[1:]:
    print(i, end= " ")

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)

N,Q=map(int,input().split())

T=[[] for i in range(N)]

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

O=[0 for i in range(N)]

for i in range(Q):
    p,x=map(int,input().split())
    O[p-1]+=x

def dfs(n):
    for i in T[n]:
        if r[i]==1:continue
        r[i]=1
        O[i]+=O[n]
        dfs(i)

r=[1]+[0]*(N-1)

dfs(0)

print(*O)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)

N,Q=map(int,input().split())

T=[[] for i in range(N)]

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

O=[0 for i in range(N)]

for i in range(Q):
    p,x=map(int,input().split())
    O[p-1]+=x

def dfs(n):
    for i in T[n]:
        if r[i]==1:continue
        r[i]=1
        O[i]+=O[n]
        dfs(i)

f=[1]+[0]*(N-1)

dfs(0,-1)

print(*O)

Submission status: Runtime Error

Solution code:
N,Q=map(int,input().split())

T=[[] for i in range(N)]

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

O=[0 for i in range(N)]

for i in range(Q):
    p,x=map(int,input().split())
    O[p-1]+=x

def dfs(n,r):
    for i in T[n]:
        if i!=r:
            O[i]+=O[n]

            dfs(i,n)

dfs(0,-1)

print(*O)

Submission status: Runtime Error

Solution code:
N,Q=map(int,input().split())

T=[[] for i in range(N)]

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

O=[0 for i in range(N)]

for i in range(Q):
    p,x=map(int,input().split())
    O[p-1]+=x

def dfs(n,r):
    for i in T[n]:
        if i==r:
            continue
        O[i]+=O[n]

        dfs(i,n)

dfs(0,-1)

print(*O)

Submission status: Runtime Error

Solution code:
def dfs(v,p=-1):
  for u in graph[v]:
    if u == p: continue
    ans[u] += ans[v]
    dfs(u,v)

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

for _ in range(Q):
  p, x = map(int,input().split())
  ans[p] += x

dfs(1)
print(' '.join([str(a) for a in ans[1:]]))

Submission status: Runtime Error

Solution code:
from collections import defaultdict

def dfs(v,p=-1):
  for u in graph[v]:
    if u == p: continue
    ans[u] += ans[v]
    dfs(u,v)

N,Q = map(int,input().split())
graph = defaultdict(list)
ans = [0 for i in range(N+1)]
for _ in range(N-1):
  a,b = map(int,input().split())
  graph[a].append(b)
  graph[b].append(a)

for _ in range(Q):
  p, x = map(int,input().split())
  ans[p] += x

dfs(1)
print(' '.join([str(a) for a in ans[1:]]))

Submission status: Runtime Error

Solution code:
import collections

n,q=map(int,input().split())
cnt=[0]*(n+1)
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)
for _ in range(q): #各頂点についてcount[v]を計算
 	v,val=map(int,input().split())
 	cnt[v]+=val
q=collections.deque()
q.append(1) #DFSのスタックによる実装、まずスタックに始点1を積む
checked=[0]*(n+1) #各頂点を見たかどうかのフラグを持っておく
while q:
 	v=q.pop()
 	checked[v]=1 #頂点を見たかどうかのフラグを更新する
 	for u in g[v]:
   		if checked[u]==1: #vの子ノードuについて、まだ見ていない頂点であればcount[u]をcount[u]+=count[v]として更新する
     		continue
   		cnt[u]+=cnt[v]
   	q.append(u) #スタックに子ノードuを積む
print(*cnt[1:]) #各頂点のcountが答えとなる

Submission status: Runtime Error

Solution code:
def get_ends():
  ends = []
  for key, value in graph.items():
    if len(value) == 0: ends.append(key)
  return ends

def get_acm_graph():
  acm_graph =  {i:[i] for i in range(1,N+1)}
  for end in ends:
    tmp_node = end
    while tmp_node != 1:
      for node in acm_graph[tmp_node]:
        if node not in acm_graph[rev_graph[tmp_node]]:
          acm_graph[rev_graph[tmp_node]].append(node)
      tmp_node = rev_graph[tmp_node]
  return acm_graph
  
N,Q = map(int,input().split())
graph = {i:[] for i in range(1,N+1)}
rev_graph = {i:-1 for i in range(1,N+1)}
counter = {i:0 for i in range(1,N+1)}
for _ in range(N-1):
  a,b = map(int,input().split())
  graph[a].append(b)
  rev_graph[b] = a

ends = get_ends()
acm_graph = get_acm_graph()

prc = {}
for _ in range(Q):
  p, x = map(int,input().split())
  if p not in prc: prc[p] = x
  else: prc[p] += x

for p, x in prc.items():
  for node in acm_graph[p]:
    counter[node] += x

print(' '.join([str(counter[i]) for i in range(1,N+1)]))

Submission status: Runtime Error

Solution code:
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<climits>
#define int long long 
#define Rint register int
#define mem(a,b) memset(a,(b),sizeof(a))
#define Temp template<typename T>
using namespace std;
typedef long long LL;

Temp inline void read(T &x){
    x=0;T w=1,ch=getchar();
    while(!isdigit(ch)&&ch!='-')ch=getchar();
    if(ch=='-')w=-1,ch=getchar();
    while(isdigit(ch))x=(x<<3)+(x<<1)+(ch^'0'),ch=getchar();
    x=x*w;
}

#define mid ((l+r)>>1)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
#define len (r-l+1)

const int maxn=200000+10;
int n,m,r=1,mod=LLONG_MAX;
//见题意 
int e,beg[maxn],nex[maxn],to[maxn],w[maxn],wt[maxn];
//链式前向星数组，w[]、wt[]初始点权数组 
int a[maxn<<2],laz[maxn<<2];
//线段树数组、lazy操作 
int son[maxn],id[maxn],fa[maxn],cnt,dep[maxn],siz[maxn],top[maxn]; 
//son[]重儿子编号,id[]新编号,fa[]父亲节点,cnt dfs_clock/dfs序,dep[]深度,siz[]子树大小,top[]当前链顶端节点 
int res=0;
//查询答案 

inline void add(int x,int y){//链式前向星加边 
    to[++e]=y;
    nex[e]=beg[x];
    beg[x]=e;
}
//-------------------------------------- 以下为线段树 
inline void pushdown(int rt,int lenn){
    laz[rt<<1]+=laz[rt];
    laz[rt<<1|1]+=laz[rt];
    a[rt<<1]+=laz[rt]*(lenn-(lenn>>1));
    a[rt<<1|1]+=laz[rt]*(lenn>>1);
    a[rt<<1]%=mod;
    a[rt<<1|1]%=mod;
    laz[rt]=0;
}

inline void build(int rt,int l,int r){
    if(l==r){
        a[rt]=wt[l];
        if(a[rt]>mod)a[rt]%=mod;
        return;
    }
    build(lson);
    build(rson);
    a[rt]=(a[rt<<1]+a[rt<<1|1])%mod;
}

inline void query(int rt,int l,int r,int L,int R){
    if(L<=l&&r<=R){res+=a[rt];res%=mod;return;}
    else{
        if(laz[rt])pushdown(rt,len);
        if(L<=mid)query(lson,L,R);
        if(R>mid)query(rson,L,R);
    }
}

inline void update(int rt,int l,int r,int L,int R,int k){
    if(L<=l&&r<=R){
        laz[rt]+=k;
        a[rt]+=k*len;
    }
    else{
        if(laz[rt])pushdown(rt,len);
        if(L<=mid)update(lson,L,R,k);
        if(R>mid)update(rson,L,R,k);
        a[rt]=(a[rt<<1]+a[rt<<1|1])%mod;
    }
}
//---------------------------------以上为线段树 
inline int qRange(int x,int y){
    int ans=0;
    while(top[x]!=top[y]){//当两个点不在同一条链上 
        if(dep[top[x]]<dep[top[y]])swap(x,y);//把x点改为所在链顶端的深度更深的那个点
        res=0;
        query(1,1,n,id[top[x]],id[x]);//ans加上x点到x所在链顶端 这一段区间的点权和
        ans+=res;
        ans%=mod;//按题意取模 
        x=fa[top[x]];//把x跳到x所在链顶端的那个点的上面一个点
    }
    //直到两个点处于一条链上
    if(dep[x]>dep[y])swap(x,y);//把x点深度更深的那个点
    res=0;
    query(1,1,n,id[x],id[y]);//这时再加上此时两个点的区间和即可
    ans+=res;
    return ans%mod;
}

inline void updRange(int x,int y,int k){//同上 
    k%=mod;
    while(top[x]!=top[y]){
        if(dep[top[x]]<dep[top[y]])swap(x,y);
        update(1,1,n,id[top[x]],id[x],k);
        x=fa[top[x]];
    }
    if(dep[x]>dep[y])swap(x,y);
    update(1,1,n,id[x],id[y],k);
}

inline int qSon(int x){
    res=0;
    query(1,1,n,id[x],id[x]+siz[x]-1);//子树区间右端点为id[x]+siz[x]-1 
    return res;
}

inline void updSon(int x,int k){//同上 
    update(1,1,n,id[x],id[x]+siz[x]-1,k);
}

inline void dfs1(int x,int f,int deep){//x当前节点，f父亲，deep深度 
    dep[x]=deep;//标记每个点的深度 
    fa[x]=f;//标记每个点的父亲 
    siz[x]=1;//标记每个非叶子节点的子树大小 
    int maxson=-1;//记录重儿子的儿子数 
    for(Rint i=beg[x];i;i=nex[i]){
        int y=to[i];
        if(y==f)continue;//若为父亲则continue 
        dfs1(y,x,deep+1);//dfs其儿子 
        siz[x]+=siz[y];//把它的儿子数加到它身上 
        if(siz[y]>maxson)son[x]=y,maxson=siz[y];//标记每个非叶子节点的重儿子编号 
    }
}

inline void dfs2(int x,int topf){//x当前节点，topf当前链的最顶端的节点 
    id[x]=++cnt;//标记每个点的新编号 
    wt[cnt]=w[x];//把每个点的初始值赋到新编号上来 
    top[x]=topf;//这个点所在链的顶端 
    if(!son[x])return;//如果没有儿子则返回 
    dfs2(son[x],topf);//按先处理重儿子，再处理轻儿子的顺序递归处理 
    for(Rint i=beg[x];i;i=nex[i]){
        int y=to[i];
        if(y==fa[x]||y==son[x])continue;
        dfs2(y,y);//对于每一个轻儿子都有一条从它自己开始的链 
    }
}

signed main(){
    read(n);read(m);
    for(Rint i=1;i<=n;i++)w[i]=0;
    for(Rint i=1;i<n;i++){
        int a,b;
        read(a);read(b);
        add(a,b);add(b,a);
    }
    dfs1(r,0,1);
    dfs2(r,r);
    build(1,1,n);
    while(m--){
        int k,x,y,z;
            read(x);read(y);
            updSon(x,y);
    }
    for(int i=1;i<=n;i++)
    {
        printf("%d%c",qRange(i,i),i==n?'\n':' ');
    }
}

Submission status: Runtime Error

Solution code:
#D
from collections import deque
n,q=map(int,input().split())
data=[[] for i in range(n)]
counter=[0 for i in range(n+1)]
for i in range(n-1):
    a,b=map(int,input().split())
        data[a].append(b)
for i in range(q):
    p,x=map(int,input().split())
    counter[p]+=x
for i in range(1,n):
    if data[i]:
        for j in range(len(data[i])):
            counter[data[i][j]]+=counter[i]
counter=deque(counter)
counter.popleft()
print(*counter)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(200000)

def dfs(v, x, G, X, visited, ans):
    visited[v] = True
    ans[v] = x
    # print(visited)

    for nv in G[v]:
        if visited[nv]:
            continue
        dfs(nv, x+X[nv], G, X, visited, ans)


def main():
    N, Q = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b = map(int, input().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)
    X = [0]*N
    for _ in range(Q):
        p, x = map(int, input().split())
        X[p-1] += x
    # print(G)
    # print(X)
    
    visited = [False]*N
    ans = [0]*N
    dfs(0, X[0], G, X, visited, ans)
    print(' '.join(list(map(str, ans))))
    

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline


def dfs(v, x, G, X, visited, ans):
    visited[v] = True
    ans[v] = x
    # print(visited)

    for nv in G[v]:
        if visited[nv]:
            continue
        dfs(nv, x+X[nv], G, X, visited, ans)


def main():
    N, Q = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b = map(int, input().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)
    X = [0]*N
    for _ in range(Q):
        p, x = map(int, input().split())
        X[p-1] += x
    # print(G)
    # print(X)
    
    visited = [False]*N
    ans = [0]*N
    dfs(0, X[0], G, X, visited, ans)
    print(' '.join(list(map(str, ans))))
    

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import math
import sys
input = sys.stdin.readline


def dfs(v, x, G, X, visited, ans):
    visited[v] = True
    ans[v] = x

    for nv in G[v]:
        if visited[nv]:
            continue
        dfs(nv, x+X[nv], G, X, visited, ans)


def main():
    N, Q = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b = map(int, input().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)
    X = [0]*N
    for _ in range(Q):
        p, x = map(int, input().split())
        X[p-1] += x
    
    visited = [False]*N
    ans = [0]*N
    dfs(0, X[0], G, X, visited, ans)
    print(' '.join(list(map(str, ans))))
    


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
rs = [map(int, input().split()) for _ in range(N-1)]
ps = [map(int, input().split()) for _ in range(Q)]

cs = [0] * N
nodes = [set() for _ in range(N)]
for n1, n2 in rs:
    nodes[n1-1].add(n2-1)

def f(n, p):
    cs[n] += p
    if not nodes[n]:
        return
    for _n in nodes[n]:
        f(_n, p)

_ps = [0] * N
for n, p in ps:
    _ps[n-1] += p

for i, p in enumerate(_ps):
    f(i, p)

print(' '.join(map(str, cs)))

Submission status: Runtime Error

Solution code:
def walk(n):
    global adj, point
    if len(adj[n])==0:
        return
    else:
        for a in adj[n]:
            point[a] += point[n]
        for a in adj[n]:
            walk(a)
N, Q = map(int, input().split())
adj = [[] for _ in range(N)]
point = [0 for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, input().split())
    adj[a-1].append(b-1)
for _ in range(Q):
    p, x = map(int, input().split())
    point[p-1] += x
walk(0)
print(" ".join(map(str, point)))

Submission status: Runtime Error

Solution code:
def walk(n, x):
    global adj, point
    if len(adj[n])==0:
        return
    else:
        for a in adj[n]:
            point[a] += x
        for a in adj[n]:
            walk(a, x)
N, Q = map(int, input().split())
adj = [[] for _ in range(N)]
point = [0 for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, input().split())
    adj[a-1].append(b-1)
for _ in range(Q):
    p, x = map(int, input().split())
    point[p-1] += x
    walk(p-1, x)
print(" ".join(map(str, point)))

Submission status: Runtime Error

Solution code:
def main():
    N, Q = list(map(int, input().split()))
    parents = {}
    ans = [0] * N

    for i in range(N-1):
        a, b = list(map(int, input().split()))
        parents[b-1] = a - 1

    for i in range(Q):
        p, x = list(map(int, input().split()))
        ans[p-1] += x

    for i in range(1, N):
        ans[i] += ans[parents[i]]

    print(' '.join(map(str, ans)))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def main():
    N, Q = list(map(int, input().split()))
    nodes = [None] * N
    ans = [0] * N

    for i in range(N-1):
        a, b = list(map(int, input().split()))

        if nodes[a-1] is None:
            nodes[a-1] = []

        nodes[a-1].append(b-1)

    # print()
    # print(nodes)

    for i in range(Q):
        p, x = list(map(int, input().split()))
        li = nodes[p-1]

        ans[p-1] += x

        if li is None:
            continue

        queue = li.copy()
        while len(queue) != 0:
            # print(queue)
            n = queue.pop(0)
            ans[n] += x

            if nodes[n] is not None:
                for next_n in nodes[n]:
                    queue.append(next_n)
        # print(i, ans)

    print(' '.join(map(str, ans)))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N, Q = list(map(int, input().split()))
p = [0] * Q
x = [0] * Q
nodes = [None] * N
ans = [0] * N

for i in range(N-1):
    a, b = list(map(int, input().split()))

    if nodes[a-1] is None:
         nodes[a-1] = []

    nodes[a-1].append(b-1)

# print()
# print(nodes)

for i in range(Q):
    p, x = list(map(int, input().split()))
    li = nodes[p-1]

    ans[p-1] += x

    if li is None:
        continue

    queue = li.copy()
    while len(queue) != 0:
        n = queue.pop(0)
        ans[n] += x

        if nodes[n] is not None:
            for next_n in nodes[n]:
                queue.append(next_n)

    # print(i, ans)

print(' '.join(map(str, ans)))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(2**5)

n,q=map(int,input().split())

l=[list() for i in range(n)]
s=[0]*(n+1)

def dfs(t,p):
  s[t]+=s[p]
  for c in l[t]:
    if c!=p:
      dfs(c,t)

for i in range(n-1):
  a,b=map(int,input().split())
  l[a-1].append(b-1)
  l[b-1].append(a-1)

for i in range(q):
  p,q=map(int,input().split())
  s[p-1]+=q

dfs(0,n)

for i in range(n):
  print(s[i],' ',end="")
print()

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())

l=[list() for i in range(n)]
s=[0]*n
c=[0]*n

def ladd(p,q):
  s[p]=c[p]+q
  for i in l[p]:
    ladd(i,s[p])

for i in range(n-1):
  a,b=map(int,input().split())
  l[a-1].append(b-1)

for i in range(q):
  p,q=map(int,input().split())
  c[p-1]+=q

ladd(0,0)

for i in range(n):
  print(s[i],' ',end="")
print()

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())

l=[list() for i in range(n)]
s=[0]*n
c=[0]*n

def ladd(p,q):
  s[p]+=q
  for i in l[p]:
    ladd(i,q)

for i in range(n-1):
  a,b=map(int,input().split())
  l[a-1].append(b-1)

for i in range(q):
  p,q=map(int,input().split())
  c[p-1]+=q

for i in range(n):
  ladd(i,c[i])

for i in range(n):
  print(s[i],' ',end="")
print()

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())

l=[list() for i in range(n)]
c=[0]*n

def ladd(p,q):
  c[p]+=q
  for i in l[p]:
    ladd(i,q)

for i in range(n-1):
  a,b=map(int,input().split())
  l[a-1].append(b-1)

for i in range(q):
  p,q=map(int,input().split())
  ladd(p-1,q)

for i in range(n):
  print(c[i],' ',end="")
print()

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())

l=[list() for i in range(n)]
c=[0]*n

def ladd(p,q):
  c[p]+=q
  for i in l[p]:
    ladd(i,q)

for i in range(n-1):
  a,b=map(int,input().split())
  l[a-1].append(b-1)

for i in range(q):
  p,q=map(int,input().split())
  ladd(p-1,q)

print(c)

Submission status: Runtime Error

Solution code:

n, q = map(int, input().split())

edge = [[] for _ in range(n)]

counter = [0] * n

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

for _ in range(q):
    a, b = map(int, input().split())
    counter[a-1] += b

parent = 0
child = 1
while True:
    while len(edge[parent]) == 0:
        parent += 1
        if parent == n-1:
            break
    if parent == n-1:
        break
    child = edge[parent].pop(0)
    edge[child].pop(0)
    counter[child] += counter[parent]
    

for i in range(n):
    print(counter[i], end=" ")
print("")

Submission status: Runtime Error

Solution code:
#not clear
class Node:
    def __init__(self,id):
        self.id = id
        self.data = 0
        self.child = []
    
    def register(self, node):
        self.child.append(node)
    
    def add(self, x):
        self.data += x
        for i in range(len(self.child)):
            self.child[i].add(x)

    def search(self, id):
        if self.id == id:
            return self
        else:
            for i in range(len(self.child)):
                node = self.child[i].search(id)
                if node != -1:
                    return node
            return -1

n, q = map(int, input().split())

a, b = map(int, input().split())
root_node = Node(a)
node = Node(b)
root_node.register(node)

for i in range(n-2):
    a, b = map(int, input().split())
    node1 = root_node.search(a)
    node2 = Node(b)
    node1.register(node2)


for i in range(q):
    a, b = map(int, input().split())
    node = root_node.search(a)
    node.add(b)

for i in range(1, n+1):
    node = root_node.search(i)
    print(node.data, end=" ")

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline

def f(ab: list, parent: list, i: int = 0):
    if len(ab[i]) == 1 and i != 0:
        return
    for j in ab[i]:
        if j != parent[i]:
            parent[j] = i
            f(ab, parent, j)

def g(ab: list, parent: list, ans: list, i: int = 0):
    if len(ab[i]) == 1 and i != 0:
        return
    for j in ab[i]:
        if j != parent[i]:
            ans[j] += ans[i]
            g(ab, parent, ans, j)

def main():
    N, Q = map(int, input().split())
    ab = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b = map(int, input().split())
        ab[a-1].append(b-1)
        ab[b-1].append(a-1)
    parent = [-1] * N
    f(ab, parent)
    ans = [0] * N
    for _ in range(Q):
        p, x = map(int, input().split())
        ans[p-1] += x
    g(ab, parent, ans)
    print(' '.join(list(map(str, ans))))
    

if __name__ == '__main__': main()

Submission status: Runtime Error

Solution code:
#include<algorithm>
#include <iostream>
#include<vector>
#include<string>
#include <iomanip>
#include <queue> 
using namespace std;

int main(){
    int n,Q;
    cin>>n>>Q;

    vector<vector<int>> adj(n+1);

    for(int i=1;i<n;i++){
        int p,c;
        cin>>p>>c;
        adj[p].push_back(c);
    }

    vector<long long> cost(n+1,0);

    for(int i=0;i<Q;i++){
        int v,c;
        cin>>v>>c;
        cost[v] += c;
    }

    queue <int> q;

    int a = 0;
    for(int i=0;i<adj.size();i++)
        if(adj[i].size()>0){
            a=i;
            break;
        }
    q.push(a);
    // vector<bool> vis(n+1,0);
    // vis[a] = 1;
    while(!q.empty()){
        int nc = q.size();
        
        while(nc>0){
            int pa = q.front();
            q.pop();
            nc--;
            long long pc = cost[pa];
            for(int i=0;i<adj[pa].size();i++){
                
                    // vis[adj[pa][i]]==1;
                    q.push(adj[pa][i]);
                    cost[adj[pa][i]] += pc;
                
            }
        }
    }

    for(int i=1;i<n+1;i++)
        cout<<cost[i]<<" ";
    cout<<endl;
}

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline
#sys.setrecursionlimit(1000000)

N,Q=map(int,input().split())
l=[[]*N for i in range(N)]
temp=[0]*N
ans=[0]*N

def dfs(i,value):
    ans[i]+=value
    for item in l[i]:
        dfs(item,value+temp[item])

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


for i in range(Q):
    p,x=map(int,input().split())
    temp[p-1]+=x

dfs(0,temp[0])

print(*ans)

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline

N,Q=map(int,input().split())
l=[[]*N for i in range(N)]
temp=[0]*N
ans=[0]*N

def dfs(i,value):
    ans[i]+=value
    for item in l[i]:
        dfs(item,value+temp[item])

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


for i in range(Q):
    p,x=map(int,input().split())
    temp[p-1]+=x

dfs(0,temp[0])

print(*ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

n, q = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n - 1)]
px = [list(map(int, input().split())) for _ in range(q)]

graph = [[] for _ in range(n + 1)]
for a, b in ab:
    graph[a].append(b)
    graph[b].append(a)

value = [0] * (n + 1)
for p, x in px:
    value[p] += x


def dfs(v, p, add):
    value[v] += add
    for x in graph[v]:
        if x == p:
            continue
        dfs(x, v, value[v])


dfs(1, 0, 0)

ans = value[1:]
print(*ans)

Submission status: Runtime Error

Solution code:
import sys
import heapq
import bisect

mod = 10**9+7
dd = ((-1,0),(1,0),(0,-1),(0,1))

def I(): return(int(sys.stdin.readline()))
def LI(): return([int(x) for x in sys.stdin.readline().split()])
def S(): return(sys.stdin.readline()[:-1])
def IR(n): return([I() for _ in range(n)])

def GCD(a,b):
    while b!=0:
        a,b = b,a%b
    return a

def LCM(a,b):
    return a * b // GCD(a,b)

def main():
    N,Q = LI()
    node=[[] for _ in range(N)]
    flag = [True for _in range(N)]
    for _ in range(N-1):
        a,b = LI()
        node[a-1].append(b-1)
        node[b-1].append(a-1)

    counter = [0] * N
    for _ in range(Q):
        p,x = LI()
        counter[p-1] += x

    cur = [[0,0]]
    while cur:
        nxt = []
        for a,c in cur:
            flag[a]=False
            counter[a]+=c
            for b in node[a]:
                if flag[b]:
                    nxt.append([b,counter[a]])
        cur = [x for x in nxt]

    r = [counter[i] for i in range(N)]

    return(" ".join(map(str,r)))

if __name__ == "__main__":
    print(main())

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())

edge = [{} for i in range(N)]

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

counters = [0] * N
for _ in range(Q):
    p, x = map(int, input().split())
    p -= 1
    counters[p] += x

def tree(root):
    for child in edge[root].keys():
        del edge[child][root]
        tree(child)

tree(0)

ans = [0] * N
def scoring(root):
    ans[root] += counters[root]
    for child in edge[root]:
        ans[child] += ans[root]
        scoring(child)

scoring(0)

for val in ans[:N-1]:
    print(val, end = " ")
print(ans[-1])

Submission status: Runtime Error

Solution code:
def main()
	import sys
	input = sys.stdin.readline
	sys.setrecursionlimit(10 ** 7)
 
 
	N, Q = map(int, input().split())
 
	T = [[]for i in range(N)]
 
	for i in range(N-1):
    	a, b = map(int, input().split())
    	T[a-1].append(b-1)
    	T[b-1].append(a-1)
 
	X = [0 for i in range(N)]
	for i in range(Q):
    	p, x = map(int, input().split())
    	X[p-1] += x
 
	def dfs(x, p):
    	for j in T[x]:
        	if j == p:
            	continue
        	X[j] += X[x]
        	dfs(j, x)
 
	dfs(0, -1)
 
	for i in range(N):
    	print(X[i], end =" ")
main()

Submission status: Runtime Error

Solution code:

n, q = [int(i) for i in input().split()]

ab = []
for i in range(n-1):
    ab.append([int(i) for i in input().split()])

px = []
for i in range(q):
    px.append([int(i) for i in input().split()])

graph = [[] for _ in range(n+1)]
for a, b in ab:
    graph[a].append(b)
    graph[b].append(a)

counter = [0] * (n+1)

for p, x in px:
    counter[p] += x

def count(node, parent=0):
    for leaf in graph[node]:
        if leaf == parent:
            continue
        counter[leaf] += counter[node]
        count(leaf, node)

count(1)

for counter_i in counter[1:]:
    print(counter_i, end=" ")