We need to solve a problem: Given a rooted tree with root 1, initially counters 0. Then Q operations: each operation j: for all vertices in the subtree of p_j, increment their counters by x_j. After all operations, output final counter values for vertices 1..N.
Constraints N, Q up to 2e5. So we need efficient processing.
This is a classic problem: subtree updates, point queries after all updates. We can flatten the tree using Euler tour (in-time, out-time) to represent subtree as a contiguous interval. Then each operation becomes a range increment (add x_j to interval [tin[p_j], tout[p_j]]). After all operations, we need the final values at each vertex, which is the sum of increments over intervals covering that vertex's position. That can be done with difference array: for each operation, add x_j at tin[p_j], subtract x_j at tout[p_j]+1 (if using 1-indexed). Then prefix sum over Euler order yields values at each position, then map back to vertex (since each vertex appears exactly once in Euler tour). However careful: Typically subtree includes all vertices whose in-time is between tin[p] and tout[p]. So we can use BIT or just array diff because we only need final values after all operations offline. So we can compute diff array of size N+2, for each operation: diff[tin[p]] += x_j; diff[tout[p]+1] -= x_j. Then prefix sum over i=1..N: val[i] = prefix sum at index i. Then answer for vertex v is val[tin[v]].
But careful: The Euler tour order: we assign tin[v] as discovery time in DFS. For subtree queries we need to ensure that the range includes all descendants exactly once. Standard: DFS order where we record each vertex at its entry time only, and subtree corresponds to range [tin[v], tout[v]] where tout[v] is exit time (or the last time of any vertex in its subtree). If we only record each vertex once (only at entry) then the subtree's vertices are exactly those with tin in [tin[v], tout[v]]. So we can use that. However we need to also record the vertex index for each tin. So we store an array order[tin] = v. Then final answer for v is val[tin[v]].
Thus solution:
Build adjacency list.
DFS from root 1, compute tin[v] and tout[v] using a timer.
Initialize diff array of size N+2 to zero.
For each operation (p, x): diff[tin[p]] += x; diff[tout[p]+1] -= x.
Compute prefix sum over i=1..N: cur += diff[i]; answer[order[i]] = cur.
Output answer[1..N] separated by spaces.
Complexity O(N+Q).
Edge Cases: Ensure timer starts at 1. Also ensure diff[tout[p]+1] exists: allocate N+2.
Now we should also consider that N and Q up to 2e5, recursion depth may cause stack overflow if using recursion. Use iterative DFS or set recursion limit large and use sys.setrecursionlimit(1e6). Python recursion limit is default 1000; N up to 2e5, so need to set recursionlimit higher. However recursion depth can be up to N in worst-case (chain tree). Python recursion may still cause RecursionError or stack overflow if recursion limit set but may exceed C stack? Usually setting recursionlimit to 1e6 works but may risk segmentation fault due to deep recursion. Safer to use iterative DFS. But for simplicity, many solutions use recursion with sys.setrecursionlimit(300000) which is okay. I'll implement iterative.
But we need to compute tin and tout. We can do iterative DFS using stack. For Euler tour that only records entry times, we can do:
timer = 1
stack = [(1, 0, 'enter')] but we need to track state. Alternatively use typical iterative DFS: push (node, parent, iterator state). Simpler: use recursion with setrecursionlimit(10**6). I think that's fine.
But ensure we have fast I/O. Use sys.stdin.buffer.
Now, we also need to account that the tree is undirected; we build adjacency list. For DFS from root, we skip parent.
Now implement.
Pseudo:
import sys
sys.setrecursionlimit(10**6)
def dfs(v, p):
global timer
tin[v] = timer
order[timer] = v
timer += 1
for to in adj[v]:
if to != p:
dfs(to, v)
tout[v] = timer - 1
But this assigns tin increasing as we enter; tout will be the last timer assigned in its subtree. Actually with this approach, after processing children, timer continues, so the last assigned timer in subtree is tout. So tout[v] = last timer in its subtree = after processing children, timer-1. So correct.
Now diff array length N+2.
Operations:
for _ in range(Q):
p, x = map(int, sys.stdin.buffer.readline().split())
diff[tin[p]] += x
diff[tout[p] + 1] -= x
Now prefix sum:
ans = [0] * (N+1)
cur = 0
for i in range(1, N+1):
cur += diff[i]
ans[order[i]] = cur
Print ' '.join(str(ans[i]) for i in range(1, N+1))
That solves.
Double-check with examples.
Example 1: N=4.
Edges:
1-2,2-3,2-4. Root 1.
DFS from 1: Enter 1 (tin1=1), then go to 2 (tin2=2), then from 2: maybe 3 then 4. Order: 1,2,3,4? Actually adjacency: 1 neighbors 2, so after 1 we go to 2. 2 neighbors 1,3,4; skip parent 1, go to 3 then 4? So tin3=3, tin4=4. So order: [1,2,3,4]. tout: for 3: tout3=3, for 4: tout4=4, for 2: tout2=4, for 1: tout1=4. Operations: p2=2 x10 -> diff[2] +=10; diff[5] -=10 (5>4 diff index ignored but we have size N+2). p1=1 x100 -> diff[1]+=100; diff[5]-=100. p3=3 x1 -> diff[3]+=1; diff[4]? tout3=3 => tout3+1=4 so diff[4] -=1. Now prefix sum: i=1: cur=100; ans[order[1]=1]=100. i=2: cur=100+10=110; ans[2]=110. i=3: cur=110+1=111; ans[3]=111. i=4: cur=111 + diff[4]? diff[4] is -1 from p3, so cur=110? Wait compute: diff[4] = -1 (from p3). Also diff[5] is -10 and -100, but not reached. So after i=3: cur=111, then at i=4: cur += diff[4] which is -1, so cur=110. ans[4]=110. So output: 100 110 111 110 matches.
Example2: N=6 tree: edges 1-2,1-3,2-4,3-6,2-5. Root1. DFS order maybe: 1 (tin1=1), then go to 2 (tin2=2), from 2: go to 4 (tin4=3), then back, then 5 (tin5=4), back to 2, back to 1, then go to 3 (tin3=5), then 6 (tin6=6). So order: 1,2,4,5,3,6. tout: 6 for all? Actually for 4: tout4=3,5: tout5=4,2: tout2=4,3: tout3=6? Wait after 3 we go to 6: tin6=6, tout6=6. Then tout3=6, tout1=6. Operations: two operations: (1,10) both. So diff[1]+=10, diff[7]-=10 twice? Actually two ops: each adds 10 at tin1=1 and subtract 10 at tout1+1=7. So diff[1] = 20, diff[7] = -20. Prefix sum: i=1 cur=20 -> ans[1]=20; i=2 cur=20; ans[2]=20; i=3 cur=20; ans[4]=20; i=4 cur=20; ans[5]=20; i=5 cur=20; ans[3]=20; i=6 cur=20; ans[6]=20. Output 20's all matches.
Works.
Now let's think about memory and performance. N up to 2e5, adjacency list with 2*(N-1) edges, fine. diff array size N+2, order size N+1.
We'll implement.
Potential pitfalls: The input edges lines: N-1 lines. Then Q lines. All integers.
We'll parse using sys.stdin.buffer.read() maybe to be faster.
Alternative: read entire input as ints via map(int, data.split()). That could be simpler but may be memory heavy with 4e5 numbers? Actually total numbers: (N-1)2 + Q2 = up to 4e5 + 4e5 = 8e5, fine. But using sys.stdin.buffer.read and splitting into ints is okay.
I'll implement:
import sys
def main():
import sys
sys.setrecursionlimit(1 << 25)
data = sys.stdin.buffer.read().split()
it = iter(data)
N = int(next(it))
Q = int(next(it))
adj = [[] for _ in range(N+1)]
for _ in range(N-1):
a = int(next(it)); b = int(next(it))
adj[a].append(b)
adj[b].append(a)
tin = [0](N+1)
tout = [0](N+1)
order = [0]*(N+1)
timer = 1
# iterative DFS to compute tin/tout
stack = [(1, 0, 0)] # (node, parent, state) where state 0=enter, 1=exit after children? But we need to record tout after children. Actually we can simulate recursion: push (node, parent, iter index) but simpler: use recursion with increased limit? I'll implement recursion for clarity, but I worry about recursion depth in Python for 2e5. Many Python solutions for this problem use recursion with sys.setrecursionlimit(300000) and pass. Let me check: AtCoder typical Python solutions use recursion for Euler tour for N=2e5. Usually it's okay if recursionlimit is set high. However Python recursion might be slower but still okay. But there is risk of recursion depth hitting C stack limit. However AtCoder's Python environment often allows recursion up to ~10^6? I've seen many solutions with recursion. Alternatively we can implement iterative DFS easily.
code
We'll implement iterative DFS:
We need to compute tin (entry time) and tout (exit time). We can do a stack of tuples (v, p, state) where state=0 means we are entering the node, state=1 means exiting.
timer = 1
stack = [(1, 0, 0)]
while stack:
v, p, state = stack.pop()
if state == 0:
tin[v] = timer
order[timer] = v
timer += 1
# push exit marker
stack.append((v, p, 1))
# push children in reverse order so that they are processed in original order? order doesn't matter.
for to in adj[v][::-1]: # reverse to maintain order if needed; not necessary.
if to != p:
stack.append((to, v, 0))
else:
tout[v] = timer - 1 # after processing children, timer is one beyond last assigned.
This works: When we pop an exit marker, timer has already been incremented for all descendants, so the last assigned timer is timer-1, which is tout[v].
Let's test with simple tree: root 1, child 2. Process:
stack start: [(1,0,0)].
pop (1,0,0): tin[1]=1, order[1]=1, timer=2. push (1,0,1). push children: adj[1] = [2], reversed same, push (2,1,0).
Next pop (2,1,0): tin[2]=2, order[2]=2, timer=3. push (2,1,1). children of 2: maybe none.
Next pop (2,1,1): tout[2]=timer-1=2.
Next pop (1,0,1): tout[1]=timer-1=2.
So tin[1]=1 tout[1]=2, tin[2]=2 tout[2]=2. Good.
So that works.
Now diff array:
diff = [0]*(N+2) # index 1..N+1
for _ in range(Q):
p = int(next(it))
x = int(next(it))
diff[tin[p]] += x
diff[tout[p] + 1] -= x
Now prefix sum:
ans = [0]*(N+1)
cur = 0
for i in range(1, N+1):
cur += diff[i]
ans[order[i]] = cur
Print results.
Now ensure we use write to stdout efficiently:
out = ' '.join(str(ans[i]) for i in range(1, N+1))
sys.stdout.write(out)
That should work.
Complexities: O(N+Q).
Now let's confirm that for large inputs it's okay.
Edge Cases: If tout[p] == N, then tout[p] + 1 = N+1, which diff has size N+2 so index N+1 is valid, and we won't prefix sum beyond N. Good.
Now double-check with a chain of N=200000, recursion iterative is fine.
So answer is done.
But note: The problem statement says each operation increments counters on vertices in the subtree rooted at p_j. That's exactly what we did.
Thus final solution.
But we must consider alternative method: propagate from root using DFS after processing operations, because each operation adds x to subtree. Could also do a single DFS that accumulates a running sum while traversing: when we go into a node, we add all x_j for operations at that node, and when leaving, subtract. That yields each node's value as sum of x for operations on ancestors. Because a node gets increment from operation at p if and only if p is ancestor. So we can do: maintain a variable cur_sum. For each node v, before processing children, we add to cur_sum the sum of x for operations where p = v. Then answer[v] = cur_sum. Then after processing children, subtract that sum. This is also O(N+Q) and avoids flattening, but requires storing operations per node. That's also fine. But our Euler tour + diff approach is simpler to implement (no need to store per node ops). Both are fine.
But our current approach using diff array after flattening is also O(N+Q). However we must note: flattening requires O(N) memory for order and tin/tout. That's fine.
We need to be careful: In the diff prefix sum approach, we need to apply all operations as range updates and then query point values. This is classic.
Now we need to output the counters for each vertex.
We've already done.
So let's write code.
I will write a function solve() and call it.
Testing with examples.
Now let's think about potential pitfalls:
Input: The lines after edges are Q lines of p_j x_j. So we must read them correctly.
Tree root is 1, but edges are given undirected. So DFS from 1.
In iterative DFS, we push children in reverse order to keep the original order? Not required. But order of traversal doesn't affect correctness as long as each vertex gets a tin and subtree interval is contiguous. Using any order is fine because the Euler tour will still produce a contiguous interval for each subtree as long as we do a DFS. In iterative approach using stack with LIFO, we may want to push children in reverse to simulate the same order as recursive (which typically uses adjacency list order). But for correctness, any DFS order works, as long as for each node, all its descendants appear consecutively in the order. That holds for any DFS that visits each node exactly once (preorder). So it's fine.
However, we need to ensure that when we push children, we don't push parent. So we check if to != p.
For large N, using recursion maybe problematic but we are using iterative.
Now, I'll produce final answer.
One more nuance: The diff array might hold values up to Q * x_j (max 2e5 * 1e4 = 2e9) which fits in 32-bit signed? 2e9 fits in 32-bit signed (max 2^31-1 = 2147483647). But Python int is unbounded, so no issue.
Now write code.
Implementation:
import sys
def solve():
import sys
sys.setrecursionlimit(1 << 25)
data = sys.stdin.buffer.read().split()
it = iter(data)
N = int(next(it))
Q = int(next(it))
adj = [[] for _ in range(N+1)]
for _ in range(N-1):
a = int(next(it))
b = int(next(it))
adj[a].append(b)
adj[b].append(a)
tin = [0](N+1)
tout = [0](N+1)
order = [0](N+1)
timer = 1
stack = [(1, 0, 0)] # (node, parent, state) 0=enter,1=exit
while stack:
v, p, state = stack.pop()
if state == 0:
tin[v] = timer
order[timer] = v
timer += 1
# push exit state after children
stack.append((v, p, 1))
# push children
for to in adj[v][::-1]: # reverse to maintain order if needed; not essential
if to != p:
stack.append((to, v, 0))
else:
tout[v] = timer - 1
diff = [0](N+2)
for _ in range(Q):
p = int(next(it))
x = int(next(it))
diff[tin[p]] += x
diff[tout[p] + 1] -= x
ans = [0]*(N+1)
cur = 0
for i in range(1, N+1):
cur += diff[i]
ans[order[i]] = cur
out = ' '.join(str(ans[i]) for i in range(1, N+1))
sys.stdout.write(out)
if name == "main":
solve()
Test with given examples.
Now, check with small cases.
Edge case: N=2, edges: 1 2, Q=1: p=2 x=5. Subtree of 2 includes only 2. So answer: 0 5. Our code: DFS order: tin[1]=1, order[1]=1, then 2: tin[2]=2, order[2]=2. tout[2]=2, tout[1]=2. Operation: diff[tin[2]=2] +=5, diff[3] -=5. Prefix: i=1: cur=0 => ans[1]=0; i=2: cur=5 => ans[2]=5. Good.
Edge case: Q=0? Constraint Q >= 1? Actually 1 ≤ Q, so at least one. But if Q=0, our code handles because loop doesn't run, diff stays zero, ans all zero. Should be fine.
Now time complexity: O(N+Q) with loops and DFS. DFS iterates each edge twice, push/pop O(N). Good.
Now consider memory: adjacency list: O(N). diff: O(N). tin/tout/order: O(N). All fine.
Now final answer.
We should add comments for clarity maybe.
Now output.
Thus the solution is ready.
Now let's produce final answer in the required format. ```python
import sys
def main():
sys.setrecursionlimit(1 << 25)
data = sys.stdin.buffer.read().split()
it = iter(data)
code
N = int(next(it))
Q = int(next(it))
# ----- build tree -----
adj = [[] for _ in range(N + 1)]
for _ in range(N - 1):
a = int(next(it))
b = int(next(it))
adj[a].append(b)
adj[b].append(a)
# ----- Euler tour (preorder) -----
tin = [0] * (N + 1)
tout = [0] * (N + 1)
order = [0] * (N + 1) # order[time] = vertex
timer = 1
# iterative DFS: state 0 = entering, 1 = exiting
stack = [(1, 0, 0)]
while stack:
v, parent, state = stack.pop()
if state == 0:
tin[v] = timer
order[timer] = v
timer += 1
# push exit marker
stack.append((v, parent, 1))
# push children (reverse order only for natural DFS, not required)
for to in adj[v][::-1]:
if to != parent:
stack.append((to, v, 0))
else:
tout[v] = timer - 1
# ----- process operations using difference array -----
diff = [0] * (N + 2) # indices 1..N+1
for _ in range(Q):
p = int(next(it))
x = int(next(it))
diff[tin[p]] += x
diff[tout[p] + 1] -= x
# ----- prefix sum -> answers -----
ans = [0] * (N + 1)
cur = 0
for i in range(1, N + 1):
cur += diff[i]
ans[order[i]] = cur
# ----- output -----
sys.stdout.write(' '.join(str(ans[i]) for i in range(1, N + 1)))