We are given a rooted tree with n vertices (1-indexed, root=1). Initially all vertices have value 0. Then q queries:
Type 1: 1 v x k
For all descendants u of v (including v itself) at distance d = dist(v, u), we add value: x - d * k. So at v (d=0) add x, at children (d=1) add x - k, at grandchildren (d=2) add x - 2k, etc.
Type 2: 2 v, print value at vertex v modulo MOD=1e9+7.
Constraints: n, q up to 3e5, so O((n+q) log n) acceptable.
We need to process many range-add updates (over subtree, but with distance-dependent additive term) and point queries. Essentially we have updates that add a value that is affine in depth (or in distance from v) across the subtree of v.
Let depth of node i be depth[i] (number of edges from root to i). Let root depth = 0. Then dist(v,u) = depth[u] - depth[v] (since tree rooted at 1, and v is ancestor of u). So for u in subtree of v, the added amount is x - (depth[u] - depth[v]) * k = x + depth[v]*k - depth[u]*k.
Let constant C_v = x + depth[v]*k. Then update adds C_v - k * depth[u] to each u in subtree of v.
Thus, each type-1 update corresponds to adding a linear function in depth[u] over the subtree: A * depth[u] + B. Actually: added = -k * depth[u] + (x + depth[v]*k). So coefficient for depth[u] is -k, constant term is (x + depth[v]*k). That is a linear expression in depth[u].
Thus we need to support many updates: each adds value to all nodes in a subtree of v, where the added value depends linearly on depth of the target node. Then point queries: retrieve sum of all updates applied that affect that node (since initial value 0). Since there are no modifications other than additions, we can process queries offline or online.
We can think of maintaining two BIT/segment trees or fenwick over Euler tour (flattening tree) to support range addition of a linear function in depth. Since depth is known per node, we can store two coefficients: coefficient for depth and constant term. For each update, we need to add to subtree range [tin[v], tout[v]]:
- add to coefficient a: -k
- add to constant term b: (x + depth[v]*k)
Then the contribution to a node u is a_u * depth[u] + b_u, where a_u and b_u are the accumulated sums of those coefficients from all updates covering u. So we need data structure supporting range add (both a and b) and point query (to retrieve total a and b for that node). Then answer = a_u * depth[u] + b_u mod MOD.
Euler tour: do DFS preorder to assign tin and tout, so subtree of v is contiguous interval [tin[v], tout[v]].
We need to support:
- range add to array a_coeff[tin..tout] += delta_a (where delta_a = -k mod MOD)
- range add to array b_coeff[tin..tout] += delta_b (where delta_b = x + depth[v]*k mod MOD)
- point query: for node u, get total_a = sum of delta_a over all updates covering u; total_b = sum of delta_b over all updates covering u; value = (total_a * depth[u] + total_b) % MOD.
We can use two Fenwick trees or segment trees with lazy propagation, but we need range add and point query. That is exactly Fenwick tree with range update point query? Wait: The typical BIT can support point update range query, but we need range update and point query. We can use BIT with difference array: To add val to range [l, r], we do BIT.add(l, val); BIT.add(r+1, -val). Then point query at i is prefix sum up to i. So we need two BITs: one for a_coeff, one for b_coeff.
That works: range add, point query in O(log n) per update and O(log n) per query. Since n and q up to 3e5, that's fine.
So algorithm:
-
Preprocess: read parent list. Build adjacency list. Do DFS from root to compute depth and Euler tour order (tin, tout). Use iterative stack to avoid recursion depth issues because n up to 3e5.
-
Have two Fenwick trees (BIT) of size n: BIT_a, BIT_b (mod MOD). Initially all zero.
-
For each query:
-
If type 1: parse v, x, k (mod MOD? Input x and k are given in range 0..MOD-1, but could be up to MOD-1). They are integers but we treat modulo MOD? Since we output modulo MOD, we can store modulo MOD. But careful: The addition to each node is x - i*k, but if we store mod MOD, the final result modulo MOD is correct. So we can keep all computations mod MOD. However, we must note that x and k could be up to 1e9+6, but within 64-bit. So we can compute delta_a = (-k) mod MOD (i.e., (MOD - k%MOD) % MOD). delta_b = (x + depth[v]*k) % MOD.
Then range add on [tin[v], tout[v]]: BIT_a.add(tin[v], delta_a); BIT_a.add(tout[v]+1, MOD - delta_a) (or -delta_a mod). BIT_b similarly.
-
If type 2: v: compute total_a = BIT_a.prefix_sum(tin[v]); total_b = BIT_b.prefix_sum(tin[v]); answer = (total_a * depth[v] + total_b) % MOD. Output answer (ensure positive mod).
Complexities: O((n+q) log n). Memory O(n).
But wait: The update formula is x - i*k, where i = distance from v to descendant. For nodes not descendants? Not added. So we covered.
However, we must consider that depth may be large but up to n. Depth up to n (3e5) fits in int.
Edge Cases: The root depth = 0. depth[v] used.
Now check example:
n=3, parents: 1 1 => tree: 1 root, children 2,3.
Compute depth: depth[1]=0, depth[2]=1, depth[3]=1.
Euler tour: let's say order: tin[1]=1, tin[2]=2, tout[2]=2, tin[3]=3, tout[3]=3, tout[1]=3.
Query: 1 1 2 1 => v=1, x=2, k=1, depth[1]=0 => delta_a = -1 mod MOD = MOD-1, delta_b = x + depth[1]*k = 2+0=2.
Range [1,3]: BIT_a: add at 1: -1, at 4: +1 (but size 3, we ignore r+1 if > n). BIT_b: add 2 at 1, -2 at 4.
Now point queries:
2 1: tin=1 => total_a = -1 mod => MOD-1, total_b=2 => answer = (MOD-1)*0 + 2 = 2 mod. OK.
2 2: tin=2 => total_a = -1, total_b=2 => answer = (-1)*1 + 2 = 1 mod. OK.
Matches.
Thus solution seems correct.
But wait, is there any nuance? The distance between two vertices is number of edges in shortest path. Since tree is rooted, v's descendants include itself. For nodes in subtree but not necessarily direct children? Yes, all descendants.
One more nuance: The update adds x - ik, where i is distance. For a descendant at distance i, the added value may become negative if x < ik. But we output modulo MOD, so we take modulo. But does the problem say "add to the number at vertex v number x; ..." and then "print the number modulo MOD"? So it's fine: we store values modulo MOD, but careful: when adding, we should do modulo arithmetic to keep within MOD. However, if we store values as mod, then the actual integer may be negative, but the modulo representation is correct. So it's fine.
Thus solution: BIT with range add point query.
Implementation details:
- Build tree: vector<vector> child(n+1) or adjacency list. Since parent list given for i=2..n, pi < i, we can add child[pi].push_back(i). This ensures a rooted tree with root 1.
- Compute tin, tout, depth via DFS. We'll use stack for iterative or recursion with limit? In Python we need iterative. In C++ recursion might be okay with n=3e5? Could cause stack overflow if depth is high. Better use iterative or increase recursion limit. We'll use iterative. Let's design.
We'll need arrays:
- tin[1..n], tout[1..n], depth[1..n].
- order: maybe vector euler; assign tin by order of visiting.
Iterative DFS: use stack of pairs (node, state) or just simulate:
stack = [(1, 0)] // (node, iterator index?) But easier: do a stack of tuple (node, parent, state) where state=0 entering, 1 exiting.
Alternatively, we can perform a standard iterative preorder and then compute tout using postorder time. We'll assign tin when first visited, push children, then after processing children assign tout. We'll maintain a separate stack for processing order.
Pseudo:
vector g[n+1];
int timer=0;
tin.resize(n+1); tout.resize(n+1); depth.resize(n+1);
stack<pair<int, int>> st; // node, iterator index? Better: use two-stack approach: one for traversal.
We can do:
stack s;
s.push(1);
vector parent(n+1);
parent[1] = 0;
vector euler; // stores nodes in order of visitation (preorder)
while (!s.empty()) {
int u = s.top(); s.pop();
// but need to handle tout later. Better to do explicit recursion simulation with state.
Let's do:
struct Frame {
int u;
int state; // 0 before processing children, 1 after processing children
int child_idx;
};
stack stk;
stk.push({1, 0, -1});
timer=0;
while (!stk.empty()) {
Frame &f = stk.top();
int u = f.u;
if (f.state == 0) {
// entering node
tin[u] = ++timer;
// set initial child index to 0
f.state = 1;
// push children onto stack in reverse order so that they are processed in original order? Not necessary.
// We'll push children later after processing? Actually we need to process children after we record entry but before exit.
// We can push children now, but we need to ensure that after all children processed, we set tout.
// Since we use state=1, we can iterate children.
if (f.child_idx == -1) {
f.child_idx = 0; // start from first child
}
// We'll attempt to push next child.
// We'll have the child list g[u].
// Process children one by one: if there is next child, push that child as new frame with state 0, and increment child_idx, but we don't want to push all at once because then we lose ability to come back.
// Better: in state 1, we will loop: while child_idx < g[u].size, push child with state 0, then break, and later when we pop back to this frame, we continue.
// But in iterative simulation, we need to resume after child returns.
// Approach: if child_idx < g[u].size(): push a new frame for that child, and increment child_idx. Then continue (so next iteration will process child). After child is processed and popped, we'll come back to this frame, and we will again check children from the updated child_idx.
// However, we need to avoid infinite loops: we need to not push the same child multiple times.
// So inside state 1, if child_idx < g[u].size, we push child and increment child_idx, then push the child's frame, and continue (i.e., break or rather we push and then continue loop? We'll let the loop iterate, and the next top is the child. That's fine.
// But we need to ensure that after pushing child, we don't process the current frame further until child is done. So after pushing child, we should continue (i.e., break out of the state handling) so that the next iteration picks the child.
// So code:
// if (f.state == 1) {
// if (f.child_idx < g[u].size()) {
// int v = g[u][f.child_idx];
// f.child_idx++;
// stk.push({v, 0, -1});
// continue;
// } else {
// // no more children
// tout[u] = timer;
// stk.pop();
// }
// }
// For state 0, we set tin and then change to state 1 and continue (so that we go into child processing immediately).
}
}
But we need to incorporate state 0 and state 1. Let's design properly.
Simpler approach: Use recursive DFS in C++ with sys.setrecursionlimit? In C++ we can set stack size or use iterative. Since typical recursion depth may be 3e5, it's dangerous, may cause stack overflow. So iterative is safer.
Another approach: Use BFS to compute depth and parent, and then do a separate Euler tour using a stack for DFS order. Many solutions use recursion in C++ for 3e5? Usually with 3e5, recursion depth might exceed typical stack (1-8 MB). It depends on compiler flags. To be safe, we can implement iterative.
Let's design iterative DFS for Euler tour.
We can simulate with two stacks: one for entering, one for exiting. Actually we can do:
vector order; // preorder list
stack st;
st.push(1);
vector parent(n+1, -1);
parent[1]=0;
while(!st.empty()) {
int u=st.top(); st.pop();
// but popping loses ability to set tout after children. So we need to push a marker for exit.
Instead, we can push pair (node, type). For type=0 entering, type=1 exiting. Then we push (node,1) after children. The algorithm:
stack<pair<int, bool>> st; // (node, is_exit)
st.push({1, false});
while (!st.empty()) {
auto [u, exit] = st.top(); st.pop();
if (!exit) {
// entering
tin[u] = ++timer;
// push exit marker
st.push({u, true});
// push children in reverse order so that they are processed in original order
for (auto it = g[u].rbegin(); it != g[u].rend(); ++it) {
int w = *it;
st.push({w, false});
}
} else {
// exiting
tout[u] = timer;
}
}
This works because we assign tin on entry and tout on exit after all children processed. timer is not incremented on exit, but tout should be the last tin among descendants. Since we assign tin incrementally, after processing all children, timer holds the max tin assigned (which is the last visited node in the subtree). So tout[u] = timer is correct (since we never decrement timer). This method is standard.
Thus we can compute tin, tout, and also depth. But we need depth as well. We can compute depth during the traversal: When we push a child, we know its depth = depth[u] + 1. But in the above stack approach, we push children without depth info. We can store depth in a separate array and set when we first encounter the node (i.e., when entering). But to know depth of child, we need depth of parent, which we know when processing parent entering. In the algorithm above, when we push children, we have the parent depth available. We can either store depth in array before pushing children, or push children with depth info. Simpler: compute depth via a separate BFS since tree is rooted and parent list is given. Actually we can compute depth from parent array directly: depth[1]=0; for i=2..n, depth[i]=depth[pi]+1. Since parents are given with pi < i, we can compute depth in a simple loop after reading parents. That's easier! Because we know the parent of each vertex from input: p2, p3, ... pn. So we can compute depth[1]=0, then for i=2..n: depth[i]=depth[pi]+1. That is O(n). So we don't need DFS for depth. Then we only need DFS for Euler tour (tin/tout). But we also need to know children adjacency for Euler tour. We can build children list from parent array. Then do Euler tour using iterative DFS as described. So we can compute depth separately.
Thus steps:
- Read n.
- Read parent list for i=2..n, store in par[i] (1-indexed). Also build children list: children[par[i]].push_back(i).
- Compute depth array: depth[1]=0; for i=2..n: depth[i] = depth[par[i]] + 1.
- Compute Euler tour (tin, tout) using iterative DFS on children adjacency.
- timer=0
- stack<pair<int,bool>> st; st.push({1, false});
- while (!st.empty()) pop top; if not exit: assign tin[u]=++timer; push exit; then push children in reverse order (so that natural order is preserved, but order doesn't matter as long as subtree range is contiguous). Actually any order yields contiguous range because subtree is contiguous in DFS order, but to be consistent we can push children in reverse order of the list. However, it's not necessary that children order be specific; but for correctness, it's fine. We'll push children in reverse order to simulate recursive DFS that processes children in the order they appear in adjacency list.
- If exit: tout[u]=timer.
- Note: For leaf, tout[u] = tin[u] = timer after assignment, which is correct.
- Initialize two Fenwick trees of size n (1-indexed). Use long long or int with mod. Since we need modulo operations, we can store as int (MOD fits in 32-bit? MOD = 1e9+7, fits in 32-bit signed? 1e9+7 > 2^31-1 (2.147e9), but it's less than 2^31? Actually 2^31-1 = 2147483647, and 1e9+7 = 1000000007, so it's within 32-bit signed int. However multiplication total_a * depth[u] may exceed 32-bit (depth up to 3e5, total_a up to MOD-1, product up to ~3e14) so need 64-bit. So use long long for intermediate.
Fenwick tree functions:
- add(index, delta) : while i <= n: bit[i] = (bit[i] + delta) % MOD; i += i & -i.
- sum(index) : res=0; while i>0: res = (res + bit[i]) % MOD; i -= i & -i. Return res.
Range add: add(l, val); add(r+1, MOD - val). (Ensure val is mod MOD.)
We'll use MOD = 1000000007.
For each query:
if type==1:
read v, x, k. x,k already < MOD? Actually constraint says 0 <= x < 1e9+7, 0 <= k < 1e9+7, so they are in [0, MOD-1]. So we can treat as modded values directly. But we need to handle negative delta_a = -k mod MOD = (MOD - k) % MOD.
Compute d = depth[v] (already known).
delta_a = (MOD - k) % MOD; // or ( -k % MOD + MOD) % MOD.
delta_b = (x + (d * k) % MOD) % MOD.
l = tin[v], r = tout[v].
BIT_a.add(l, delta_a); if r+1 <= n: BIT_a.add(r+1, MOD - delta_a). Same for BIT_b.
if type==2:
read v.
pos = tin[v].
total_a = BIT_a.sum(pos) % MOD.
total_b = BIT_b.sum(pos) % MOD.
ans = (total_a * depth[v] % MOD + total_b) % MOD.
output ans.
Check: The depth[v] is the node's depth from root. But we used delta_a as coefficient for depth[u] in contribution: total_a * depth[u] + total_b. This matches our derivation: For each update covering u, we added -k to a_coeff and (x + depth[v]k) to b_coeff, so the total contribution from that update is -kdepth[u] + (x + depth[v]*k). Summed over updates gives total_a * depth[u] + total_b, where total_a is sum of -k and total_b is sum of (x + depth[v]*k). So correct.
But we must ensure that depth[u] is the same as the depth used in the formula. Yes.
Now we must be careful about mod: total_a can be negative modulo, but we store as positive mod. Multiplying depth[u] (positive) and adding total_b yields correct modulo. So fine.
Potential pitfalls:
- Overflows: Use long long for intermediate products; mod after each operation.
- BIT size: n up to 3e5, so arrays of size n+2 fine.
- Euler tour using stack: ensure we push children in correct order; but order doesn't matter for correctness of subtree intervals? Actually, for any DFS order that respects subtree contiguity, each subtree corresponds to a contiguous interval. The standard DFS preorder where we assign tin when first visiting a node, and then recursively visit all children, yields that property. In our iterative method with exit markers, we push children onto stack and then process them; because we push children in reverse order, we simulate recursive preorder where children are visited in the order they appear in the list. This yields a valid DFS order. So subtree will be contiguous. So it's fine.
Edge Cases:
- When v is leaf, tin[v]=tout[v].
- Update where k=0: then delta_a = 0? Actually -0 = 0, delta_a = 0. So we add only constant.
- When x=0, k=0: update adds 0.
- When k > MOD? Input guarantees k < MOD, so safe.
Now test with some small random.
But wait: there is subtlety: The update is defined as adding to vertex v number x; to descendants at distance 1: add x - k; distance 2: x - 2k, etc. The formula we derived is x - (depth[u]-depth[v])*k = x + depth[v]*k - depth[u]*k. This holds as long as depth[u] >= depth[v]. Since we only add to descendants, it's fine.
Now we should confirm with more complex tree: Suppose v is not root, and we have an update. Our method uses depth array computed from root, which works because distance from v to u is depth[u] - depth[v]. Yes.
Now complexities: O(n + q log n). Good.
One more nuance: The BIT approach uses range add and point query, which is O(log n) per update and O(log n) per query. Since there are up to 3e5 queries, it's fine.
But we have to store two BITs. Implementation in C++ should be fast. We'll use vector or vector for BIT, but do modulo operations.
Now consider the possibility of negative delta_a. We'll compute delta_a = (MOD - k) % MOD. But if k=0, then (MOD-0)%MOD = 0? Actually MOD%MOD = 0? Wait: (MOD - 0) % MOD = 0? Because MOD - 0 = MOD, MOD % MOD = 0. So correct. For k>0, (MOD - k) gives a positive number less than MOD if k<MOD, but MOD - k is in [1, MOD-1], and mod MOD gives same. So fine.
Alternatively, we can compute delta_a = (-k % MOD + MOD) % MOD.
Now, delta_b = (x + depth[v]*k) % MOD. depth[v] up to 3e5, k up to 1e9+6, product up to 3e14, fit in long long. Compute (depth[v] % MOD) * k % MOD, then add x, mod.
Now, range add: For BIT, we need to add delta to index l and subtract at r+1. Since we store modulo values, we need to ensure that subtract is done modulo MOD: add(r+1, MOD - delta) (if delta != 0). If delta is 0, it's fine.
Edge: If r == n, then r+1 > n, we skip the second update. BIT size is n, index range 1..n. So condition.
Now for queries type 2, we compute sum of BIT_a up to tin[v] and BIT_b up to tin[v]. The BIT prefix sum returns cumulative sum mod MOD.
Now, answer = (total_a * depth[v] + total_b) % MOD. We must take care that total_a may be stored as mod (0..MOD-1). But total_a is sum of -k_i mod MOD for each covering update. So total_a = (Σ (-k_i) mod MOD). But the true sum (as integer) might be negative, but modulo representation yields same result when multiplied by depth[v] and added to total_b mod MOD? Actually, the contribution from each update is -k_i*depth[u] + (x_i + depth[v_i]*k_i). Summing over updates: Σ (-k_i) * depth[u] + Σ (x_i + depth[v_i]*k_i). So if we compute Σ (-k_i) modulo MOD, and then multiply by depth[u] modulo MOD, that gives (Σ (-k_i) * depth[u]) mod MOD, which is same as the true sum mod MOD because multiplication distributes mod. However, careful: The expression Σ (-k_i) * depth[u] is equal to depth[u] * Σ (-k_i). So using the modded Σ (-k_i) is fine, as long as we multiply mod MOD. So it's correct.
Thus solution stands.
But wait: There is an alternative perspective: The update can be expressed as adding f(u) = A * depth[u] + B for nodes in subtree. So our approach is correct.
Now we should ensure that the Euler tour intervals are correct. Since tree is rooted and we traverse from root, each subtree is contiguous. This is standard.
Now test with simple non-root updates.
Example: n=4, parents: 1,1,2 (meaning: p2=1, p3=1, p4=2). So tree: 1->2,3; 2->4. depths: 1:0, 2:1, 3:1, 4:2.
Euler order: Let's simulate DFS: start 1, children 2,3. If we push children in order 2,3 (reverse? If we push children in reverse order to maintain natural order, we push 3 then 2 so that 2 gets processed first? Actually typical recursive DFS would process children in order they appear. So if we push children in reverse order, then the first child popped from stack is the last pushed, which would be the first in original order? Let's illustrate: children list [2,3]. If we push in reverse: push 3 then 2. Then stack top is 2 (since last pushed? Actually if we push 3 then 2, the order of pushes: push(3), push(2). Then stack top is 2 because LIFO. So 2 gets processed first, then after its subtree, we later process 3. That yields order: 1,2,4,3 (if we process 2 before 3). That's a valid DFS order. Subtree of 2 would be nodes 2 and 4, which should be contiguous: tin[2]=2, tin[4]=3? Let's compute: tin[1]=1, then process 2: assign tin[2]=2, then process children of 2: only 4, assign tin[4]=3. After finishing 4, tout[4]=3, then tout[2]=3. Then back to 1, process 3: tin[3]=4, tout[3]=4. So subtree of 2 is [2,3] contiguous. Subtree of 1 is [1,4]. So fine.
Thus order not important.
Now check update: 1 2 x k: v=2. depth[2]=1. delta_a = -k, delta_b = x + depth[2]k = x + k. For node 4 depth=2, contribution from this update is -k2 + (x+k) = x - k. Which matches distance: dist(2,4)=1? Actually distance from 2 to 4 is 1 (edge 2-4) -> expected add x - k? Wait distance=1, so should be x - k? But our formula gave x - k? Yes, correct. For node 2 distance=0, add x. Good.
Now query: 2 4 should get value = x - k. Good.
Our BIT: add to range tin[2]=2..3: a += -k, b += x+k. For node 4 tin=3: total_a = -k, total_b = x+k. total_a * depth[4] + total_b = -k*2 + x+k = x - k. Works.
Now verify the effect on other nodes not in subtree: Node 3 is not in subtree of 2; its tin=4, not in range, so no update. Good.
Thus algorithm correct.
Now time to implement.
Implementation steps in code:
-
Define MOD = 1000000007.
-
Read n.
-
vector parent(n+1); parent[1] = 0.
-
vector<vector> children(n+1);
-
for i from 2 to n: read p; parent[i]=p; children[p].push_back(i).
-
Compute depth: vector depth(n+1); depth[1]=0; for i=2..n: depth[i] = depth[parent[i]] + 1.
-
Compute tin, tout: vector tin(n+1), tout(n+1);
int timer=0;
stack<pair<int, bool>> st; // bool indicates exit?
st.push({1, false});
while (!st.empty()) {
auto [u, isExit] = st.top(); st.pop();
if (!isExit) {
tin[u] = ++timer;
st.push({u, true}); // push exit marker
// push children in reverse order
for (auto it = children[u].rbegin(); it != children[u].rend(); ++it) {
st.push({*it, false});
}
} else {
tout[u] = timer;
}
}
// Note: This will assign tin for all nodes and tout. timer should be n after traversal.
-
Initialize BITs: two vectors bit_a(n+2, 0), bit_b(n+2, 0) (since we may need up to n+1 for r+1). We'll implement BIT class with size n.
Class BIT {
private:
vector tree;
int n;
public:
BIT(int sz) : n(sz), tree(sz+2, 0) {}
void add(int idx, long long val) {
val %= MOD;
if (val < 0) val += MOD;
while (idx <= n) {
tree[idx] = (tree[idx] + val) % MOD;
idx += idx & -idx;
}
}
long long sum(int idx) {
long long res = 0;
while (idx > 0) {
res = (res + tree[idx]) % MOD;
idx -= idx & -idx;
}
return res;
}
};
But careful: In add, we need to ensure val is already modded. We'll mod.
Now process queries:
int q; cin>>q;
while(q--){
int type; cin>>type;
if(type==1){
int v; long long x, k; cin>>v>>x>>k; // x,k < MOD, but read as long long.
x %= MOD; k %= MOD;
long long delta_a = (MOD - k) % MOD; // or ( -k % MOD + MOD )%MOD
long long delta_b = (x + (depth[v] * k) % MOD) % MOD;
int l = tin[v];
int r = tout[v];
BIT_a.add(l, delta_a);
if (r+1 <= n) BIT_a.add(r+1, MOD - delta_a);
BIT_b.add(l, delta_b);
if (r+1 <= n) BIT_b.add(r+1, MOD - delta_b);
} else {
int v; cin>>v;
long long total_a = BIT_a.sum(tin[v]);
long long total_b = BIT_b.sum(tin[v]);
long long ans = (total_a * depth[v] % MOD + total_b) % MOD;
cout << ans << "\n";
}
}
But ensure that when we add MOD - delta, we mod again? Actually BIT.add expects val modulo MOD; we can compute (MOD - delta_a) % MOD and pass.
Edge Cases:
- If delta_a = 0, then MOD - delta_a = MOD, which mod MOD is 0. So we can skip if delta_a == 0, but not necessary.
Now check for possible overflow: depth[v] up to 3e5, total_a up to MOD-1, product up to 3e14, fits in long long (9e18). So fine.
Now final answer.
Testing with provided example: we already did.
Now we should test with another example: n=1 (single node). No parent list? Actually n=1, then second line is empty? Input format: "The second line contains n - 1 integers p2, p3, ... pn". If n=1, there are no numbers, so second line may be empty or not present? Usually, for n=1, the second line is empty; we should handle reading: after reading n, if n>1 read the parent list else skip. But the problem statement says n>=1, and second line contains n-1 integers. So if n=1, no numbers. We can read line maybe with getline? Simpler: if n>1 then read the list, else just skip (maybe read and ignore? But there will be a newline). We'll just read the next line with getline? Not ideal. In C++, we can read the number of parents conditionally: after reading n, if n>1, read n-1 integers; else we still need to consume the newline before reading q. So we can do: if (n>1) { for i=2..n: cin >> p; ... } else { // nothing } but note that the newline after n might cause issues if we just skip? Actually cin >> n reads integer and leaves the newline. Then reading next tokens: if n>1, we expect n-1 ints, and cin will parse them correctly ignoring whitespace. If n==1, there are no ints, so we should not attempt to read any. But the next input line after the newline might be q. So we just do nothing. So it's fine.
Now compute depth: depth[1]=0.
Euler tour: tin[1]=1, tout[1]=1.
Now process queries: type 1 1 x k: delta_a = -k, delta_b = x+0*k = x, update range [1,1], etc. Queries 2 1: works.
Now verify that depth array is computed for all nodes. For n=1, depth[1]=0.
Now complexity: O((n+q) log n) = ~ (6e5)log2(3e5) ~ 6e519 ~ 11.4e6 operations, fine.
Now memory: children adjacency list: total edges n-1, so O(n). BIT arrays: O(n). Euler tour arrays O(n). All fine.
Potential pitfalls: Stack overflow in DFS iterative? The stack holds at most depth of tree. Since depth could be up to n, we may push many pairs. In worst case tree is a chain of 3e5 nodes. Our stack simulation with exit markers will push at most 2n items? Actually in a chain, the stack will contain at most O(depth) frames: For a chain 1-2-3-...-n, when we push node 1 with exit false, then pop it, assign tin[1], push exit true, then push child (node 2) false (since children list has one child, reverse order doesn't change). Then stack now contains: bottom: (1,true), top: (2,false). Then process 2: assign tin[2], push exit true, push child (3) false. So stack height: number of active nodes plus their exit markers? Actually at some point, stack will contain (1,true), (2,true), (3,true) ... plus the current node's false? Let's simulate: after processing node 1, stack: (1,true). Then push child 2 false -> stack: (1,true), (2,false). Process 2: pop (2,false), assign tin[2], push (2,true), push child 3 false -> stack becomes: (1,true), (2,true), (3,false). Process 3: pop (3,false) -> assign tin[3], push (3,true), push child 4 false -> stack: (1,true), (2,true), (3,true), (4,false). So stack height grows linearly with depth. The maximum size is about 2depth (each node has an exit marker and a false for current). Depth max 3e5, so stack size about 600k, which might be okay if we use a stack from heap (std::stack uses deque, dynamic allocation). So memory is fine, not recursion stack. So safe.
Now what about time for DFS? O(n) each node visited once, each child pushed.
Now finalize.
Potential Issue: The update range might be large, but BIT handles.
Now note: We must use 64-bit for BIT internal sums because while accumulating many updates, the values can become large (each update adds up to MOD-1, and number of updates up to 3e5, so sum can be up to 3e5*1e9 ~ 3e14, which fits in 64-bit, but if we use int, could overflow. So use long long.
Now about modulo: When we compute BIT sum, we keep mod each addition to keep values within MOD? Actually we need only the final answer mod MOD. But we can store BIT entries modulo MOD, because we only need prefix sums mod MOD. However, the BIT's prefix sum function returns mod MOD after each addition mod MOD. That's acceptable because (a mod MOD + b mod MOD) mod MOD = (a+b) mod MOD. But careful: The BIT adds delta values to nodes; these delta values are already mod MOD. Then the prefix sum is the sum of these mod values, which equals the sum of the original deltas modulo MOD. That's correct for our purposes. However, there is nuance: The range add uses difference array: we add delta at l, and subtract delta at r+1. The prefix sum at i gives the total delta added to i. Since we mod each addition, the prefix sum modulo MOD gives the correct total delta modulo MOD. That's fine.
Now, consider when we compute total_a * depth[u] + total_b, both total_a and total_b are mod MOD. Multiplying by depth (which we treat as integer, not modded) and then mod is okay because depth is not reduced modulo MOD? Actually depth is just an integer, we treat it as regular integer. But the expression should be computed modulo MOD. So we compute (total_a * depth[u]) % MOD, where total_a is modulo MOD. This yields ( (Σ (-k_i) mod MOD) * depth[u] ) mod MOD. But note that Σ (-k_i) may be large; the true value is Σ (-k_i). Multiplying by depth[u] and taking mod yields (depth[u] * Σ (-k_i)) mod MOD. Since (Σ (-k_i) mod MOD) * depth[u] mod MOD equals (depth[u] * Σ (-k_i)) mod MOD only if we also reduce depth[u] modulo MOD? Actually multiplication mod MOD: (a mod MOD) * b mod MOD = (ab) mod MOD, provided b is an integer. But if b is not modulo reduced, it's still fine: (a mod MOD) * b = (a - MODq)b = ab - MODqb, which mod MOD is a*b mod MOD. So it's correct. So we can treat depth as ordinary integer (up to 3e5) and multiply with total_a (mod MOD) and then mod. So okay.
Now for total_b: sum of (x_i + depth[v_i]*k_i) mod MOD. That is correct.
Thus solution stands.
Now we need to implement in C++.
But before finalizing, consider alternative approach: We could also use two BITs for depth and constant, as we did.
Double-check for potential off-by-one: tin values range 1..n. BIT size n. For range add, we add at l, and if r+1 <= n, add negative at r+1.
Now we must ensure that depth array computed correctly. Since pi < i, we can compute depth in increasing order from 2 to n: depth[i] = depth[par[i]] + 1. This works because parent index is smaller, so depth[par[i]] already computed. Good.
Now about reading input: q up to 3e5, use fast I/O: ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0).
Now let's code.
But we also need to be careful about data types: Use int for indices; depth as int (since max 3e5). For BIT, use long long for internal sums to avoid overflow when adding many mod values? Actually each BIT node can accumulate many updates, each up to MOD-1, and number of updates affecting a BIT node is O(log n) per update? Wait, each update performs add at O(log n) BIT positions. So each BIT index may receive many updates: at most number of updates times (but each update touches O(log n) indices). In worst case, all updates could affect the same BIT index? For point updates? But range update uses two point updates; each BIT.add touches O(log n) positions. So each BIT node (like tree[i]) may accumulate up to O(q log n) contributions. q=3e5, log n~19, so total contributions per BIT node could be up to 5.7e6, each up to MOD-1, sum up to ~5.7e6*1e9 = 5.7e15, which still fits in 64-bit (9e18). So using long long is safe. But we store modulo MOD anyway; but if we store long long without modding after each addition, it could overflow 64-bit? 5.7e15 < 9e18, safe. But to be safe and keep numbers small, we can mod after each addition. That will keep numbers within MOD. But careful: When we do BIT.add, we pass delta mod MOD and then inside add we do tree[idx] = (tree[idx] + val) % MOD. This ensures tree[idx] stays in [0, MOD-1]. So long long is fine. So we can store as long long.
But note: In BIT.add for the negative update (MOD - delta), we compute val = (MOD - delta) % MOD, which is 0 if delta==0. That's fine.
Now let's test with a random small case to verify.
But wait, there is a nuance: The BIT's prefix sum returns sum of values stored at indices, which are modded. Since we store each addition modded, the sum of modded values may not equal the mod of sum of original values if we didn't mod each addition? Actually if we store each addition modded, and then sum them modded, we are effectively computing (Σ (delta_i mod MOD)) mod MOD. This equals (Σ delta_i) mod MOD only if we don't lose information due to modulo before summation? But modulo is linear: (a mod M + b mod M) mod M = (a+b) mod M. So it's okay as long as we perform mod after each addition? But careful: When we store tree[idx] as (tree[idx] + val) % MOD, we are effectively applying modulo to the running sum at that node. If we later sum multiple such nodes for a prefix sum, we are summing values that have been reduced modulo MOD. Since addition and modulo commute? Actually, suppose we have contributions v1, v2, v3 to tree[idx]. Instead of storing sum(v_i) mod MOD, we are doing tree[idx] = ( (tree[idx] + v1 % MOD) % MOD ), then later add v2: tree[idx] = (tree[idx] + v2) % MOD, etc. The final tree[idx] equals (v1 + v2 + v3) % MOD. So it's exactly the sum mod MOD. So it's fine.
Thus BIT with modulo operations yields correct prefix sums modulo MOD.
Now, we need to compute delta_a as (-k) mod MOD. Since k is already less than MOD, delta_a = (MOD - k) % MOD. But if k==0, then delta_a=0, which is fine.
Now, what about negative numbers? We always convert to positive modulo.
Now, let's implement.
But we need to be cautious about the Euler tour: In our iterative DFS, we push children in reverse order. That's fine. But ensure that the children list for each node is built in order from input. Since we read parents for i from 2..n in order, we push i into children[pi] in that order. That order may affect the DFS order but it doesn't matter.
Now test with chain n=3: parents: 1 2? Actually for n=3: p2=1, p3=2. Build children: children[1]:{2}; children[2]:{3}. Depth: d[1]=0, d[2]=1, d[3]=2.
DFS: push 1 false. pop: assign tin[1]=1, push exit true, push children of 1 reversed: only 2 -> push (2,false). stack: (1,true) (2,false). pop (2,false): assign tin[2]=2, push (2,true), push children of 2 reversed: only 3 -> push (3,false). stack: (1,true),(2,true),(3,false). pop (3,false): assign tin[3]=3, push (3,true), children of 3 none. stack: (1,true),(2,true),(3,true). pop (3,true): tout[3]=3. pop (2,true): tout[2]=3. pop (1,true): tout[1]=3. So subtree intervals: node2: tin=2, tout=3 includes node3. Good.
Now run update: 1 2 x k. depth[2]=1 => delta_a = -k, delta_b = x + k. Range [2,3]. For node3 (tin=3): total_a = -k, total_b = x+k. ans = -k*2 + x+k = x - k. Dist(2,3)=1, expected x - k. Good.
Now for node1: not updated because tin=1 not in [2,3]? Actually node1 is not descendant of 2, so correct.
Now test with multiple updates:
Update1: 1 1 x1 k1. Update2: 1 2 x2 k2. Then query node3.
We compute: contributions:
From update1: depth[3]=2, depth[1]=0: add x1 - 2k1.
From update2: add x2 - (dist(2,3)=1)*k2 = x2 - k2.
Total: x1 + x2 - 2k1 - k2.
Our BIT:
For update1: delta_a1 = -k1, delta_b1 = x1 + depth[1]*k1 = x1, range[1,3].
For update2: delta_a2 = -k2, delta_b2 = x2 + depth[2]*k2 = x2 + k2, range[2,3].
At node3: total_a = -k1 - k2, total_b = x1 + (x2 + k2) = x1 + x2 + k2.
Then total_a*depth[3] + total_b = (-k1 - k2)*2 + x1 + x2 + k2 = -2k1 -2k2 + x1 + x2 + k2 = x1 + x2 - 2k1 - k2. Correct.
So correct.
Now we must also consider that the update value x - i*k might become negative and we are adding it to the node's value. Since we are only interested in modulo at output, it's fine.
Thus solution is straightforward.
Now we need to ensure that we use 64-bit for intermediate multiplication in BIT sum? BIT sum returns long long mod MOD. But in answer computation, we compute total_a * depth[v] which may be up to (MOD-1)*3e5 ~ 3e14, within long long. So compute as (total_a % MOD) * depth[v] % MOD.
Now time to write final code.
But before finalizing, consider memory: BIT with size n+2, each tree array of long long; depth, tin, tout, parent arrays int; children adjacency vector of vectors int; That's fine.
Potential improvements: Could avoid children list for Euler tour if we compute tin/tout using parent array? Possibly compute using recursion based on parent order but it's easier with children list.
Now we should also consider that the input format: after n, the next line contains n-1 integers. We'll read them using a loop.
Now about reading q and queries: Each query line: first integer type. For type 1, then v, x, k. For type 2, then v.
Use scanf for speed or cin with ios_base. For 3e5 lines, cin with sync off is fine.
Now implement:
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int MAXN = 300000 + 5;
int n;
vector<vector> children;
vector depth;
vector tin, tout;
struct BIT {
int n;
vector bit;
BIT(int n_) : n(n_), bit(n_+2, 0) {}
void add(int idx, long long val) {
val %= MOD;
if (val < 0) val += MOD;
while (idx <= n) {
bit[idx] = (bit[idx] + val) % MOD;
idx += idx & -idx;
}
}
long long sum(int idx) {
long long res = 0;
while (idx > 0) {
res = (res + bit[idx]) % MOD;
idx -= idx & -idx;
}
return res;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
children.resize(n+1);
depth.resize(n+1);
tin.resize(n+1);
tout.resize(n+1);
// parent for vertices 2..n
for (int i = 2; i <= n; i++) {
int p;
cin >> p;
children[p].push_back(i);
}
// compute depth
depth[1] = 0;
for (int i = 2; i <= n; i++) {
// parent? we don't have parent array directly, but we can compute depth via BFS or using children? Actually we only have children list; we need parent to compute depth efficiently. Could do BFS from root. But we can also compute depth in the same loop if we stored parent. So better store parent array from input.
// We didn't store parent, but we can store it. Let's store parent[i] from input.
}
But we didn't store parent yet. In the reading loop we only built children. We can also store parent array as we read. Let's modify: create parent array of size n+1, and fill.
Implementation: vector parent(n+1);
for (int i=2; i<=n; i++) {
cin >> parent[i];
children[parent[i]].push_back(i);
}
Then compute depth: for i=2..n: depth[i] = depth[parent[i]] + 1.
So we need parent array.
Add: vector parent(n+1, 0);
Then reading loop: cin >> parent[i]; children[parent[i]].push_back(i);
That works.
Now compute depth: depth[1] = 0; for i=2..n: depth[i] = depth[parent[i]] + 1.
Now Euler tour:
stack<pair<int, bool>> st;
st.push({1, false});
int timer = 0;
while (!st.empty()) {
auto [u, isExit] = st.top();
st.pop();
if (!isExit) {
tin[u] = ++timer;
st.push({u, true}); // exit later
// push children in reverse order
for (auto it = children[u].rbegin(); it != children[u].rend(); ++it) {
st.push({*it, false});
}
} else {
tout[u] = timer;
}
}
Now BITs: BIT bitA(n), bitB(n);
Process q:
int q; cin>>q;
while(q--) {
int type; cin>>type;
if (type == 1) {
int v; long long x, k; cin>>v>>x>>k;
x %= MOD; k %= MOD;
long long delta_a = (-k) % MOD;
if (delta_a < 0) delta_a += MOD;
long long delta_b = (x + (depth[v] * k) % MOD) % MOD;
int l = tin[v], r = tout[v];
bitA.add(l, delta_a);
if (r+1 <= n) bitA.add(r+1, MOD - delta_a);
bitB.add(l, delta_b);
if (r+1 <= n) bitB.add(r+1, MOD - delta_b);
} else {
int v; cin>>v;
long long total_a = bitA.sum(tin[v]);
long long total_b = bitB.sum(tin[v]);
long long ans = (total_a * depth[v] + total_b) % MOD;
cout << ans << "\n";
}
}
Return 0.
Now test with the given example.
Let's simulate quickly.
n=3, parent[2]=1, parent[3]=1. children[1]={2,3}. depth[1]=0, depth[2]=1, depth[3]=1.
Euler: timer=0.
Start: push(1,false).
pop (1,false): tin[1]=1, push(1,true). push children reverse: children[1] order {2,3}, reverse push (3,false), (2,false). stack now (top to bottom? LIFO: after pushes: push(3,false) then push(2,false) so stack: (2,false) on top? Actually order of pushes: first push(3,false) then push(2,false). So top is (2,false). So we pop (2,false) next.
pop (2,false): tin[2]=2, push(2,true). children[2] empty -> no pushes. stack now: (1,true), (3,false)? Wait before processing (2,false), stack had: (1,true), (3,false), (2,false)?? Let's step carefully:
Initial stack: [(1,false)].
Pop (1,false):
- tin[1]=1
- push (1,true)
- push children reversed: for each child in children[1] = [2,3], reverse order: push (3,false) then (2,false)
Now stack contents (top to bottom): (2,false) (since last pushed), then (3,false), then (1,true). Actually push order: first push (3,false), then push (2,false). So after pushes, stack: top = (2,false), then (3,false), then (1,true). Yes.
Now pop top: (2,false):
- tin[2]=2
- push (2,true)
- children[2] none, no pushes
Now stack: top = (3,false) (next), then (2,true), then (1,true). Actually after pushing (2,true), stack becomes: (2,true) top? Wait we popped (2,false), then we push (2,true). So after pushing, new top is (2,true). But we need to see order: we popped (2,false) from stack, then we push (2,true). That push puts (2,true) on top. Then stack contents: (2,true), (3,false), (1,true). So top is (2,true). So next pop is (2,true):
- tout[2]=timer, currently timer=2 (since last assigned tin was 2). So tout[2]=2.
- no other.
Stack now: (3,false), (1,true). Pop (3,false):
- tin[3]=3, timer=3.
- push (3,true)
- children none
Stack now: (3,true), (1,true). Pop (3,true): tout[3]=3. Stack: (1,true). Pop (1,true): tout[1]=3. Done.
Thus tin: 1,2,3; tout: 1? Actually tout[1]=3, tout[2]=2, tout[3]=3. Subtree of 1: [1,3]; subtree of 2: [2,2]; subtree of 3: [3,3]. Good.
Now process queries: As before works.
Now ensure that for node 2, tout[2]=2, so range [2,2]. Good.
Now test with chain n=3: parents: 1,2.
children[1]={2}, children[2]={3}.
depth[1]=0, depth[2]=1, depth[3]=2.
Euler: as earlier, tin[1]=1, tin[2]=2, tin[3]=3; tout[1]=3, tout[2]=3, tout[3]=3.
Now update: 1 2 x k => delta_a=-k, delta_b=x+k, range [2,3]. For node3: works.
Now type2 query for node2: total_a = -k, total_b = x+k, depth[2]=1 => -k*1 + x+k = x. Good (distance 0). For node3: as computed.
Now test with multiple updates overlapping: Should be fine.
Now consider if v is leaf: range l = r. BIT add adds delta at l, and if r+1 <= n, subtract at r+1.
Now for leaf with tin = some idx, and r+1 may be <= n if leaf is not the last node. So we do both.
Now potential error: In BIT add, we used while (idx <= n). Since our BIT size is n, indexing up to n. When we add at r+1 if r+1 <= n, it's fine.
Now for r = n, r+1 = n+1 > n, we skip, so only add at l.
Now consider n=1: BIT size =1, tin[1]=1, tout[1]=1. For update: l=1, r=1, r+1=2 > n, so only add at 1. Good.
Now for query: BIT.sum(1) returns value.
Now all good.
Now consider the fact that delta_a could be negative after modulo? We ensure it's positive mod.
Now about reading queries: type 1 lines have three integers after type. We'll read them.
Now final code as described.
Now double-check: we used depth array which is of type int. In multiplication depth[v]*k, we cast to long long to avoid overflow. We'll compute (depth[v] * k) % MOD. depth[v] is int but can be up to 3e5, k up to MOD-1, product fits in long long. So compute (1LL * depth[v] * k) % MOD.
Now about BIT's sum: returns long long modded. Multiplication total_a * depth[v] might be up to (MOD-1)*3e5 ~ 3e14, so use (total_a % MOD) * depth[v] % MOD. Since total_a is already mod MOD, it's fine.
Now consider that total_a could be negative if we didn't mod? But we store modded, so it's positive. So final answer may be incorrect if the true total_a is negative? Because we use modulo arithmetic, it's fine; negative mod becomes positive. So answer mod MOD is correct.
Now finalize.
Potential optimization: Use int for BIT if we always mod; but to be safe use long long.
Now we produce final solution.
But wait: There might be a nuance: The query "add to the number at vertex v number x; to the numbers at the descendants of vertex v at distance 1, add x - k; ... distance i, add x - (i·k)". This includes all descendants at any depth, but what about vertices that are not descendants? Not affected. So our subtree constraint correct.
Now check for large values: x and k up to 1e9+6, so we mod them. However, note that the actual arithmetic might be done in integers before modulo. But we only need final modulo. So modding intermediate is fine because modulo is applied to each addition. But careful: The addition to each vertex is x - i*k, which could be negative. In modular arithmetic, adding a negative number is equivalent to adding MOD minus its absolute value mod MOD. That's exactly what we are doing because we compute contributions modulo MOD. So correct.
Now we should consider if there is any need to use 64-bit for depth? depth up to 3e5 fits in int.
Now ready to code.
But the problem statement: "Initially all vertices contain number 0. Then come q queries, each query has one of the two types:" etc. So we are good.
Now test with some random small n and random queries to verify with brute force.
We can mentally test:
n=2: parent[2]=1. children: 1:{2}. depth[1]=0, depth[2]=1.
Euler: tin[1]=1, tin[2]=2, tout[1]=2, tout[2]=2.
Queries:
1 2 5 2 -> v=2, x=5, k=2. depth[2]=1. delta_a = -2 mod = MOD-2, delta_b = 5 + 12 = 7. range [2,2] (only vertex 2). So node2 gets total_a = -2, total_b=7. So ans = -21 +7 =5. That's correct: at v itself add x=5.
2 2 -> output 5.
Now another update: 1 1 3 1 -> v=1, depth=0, delta_a=-1, delta_b=3. range [1,2]. Node1: total_a = -1, total_b=3 => ans = -10+3=3. Node2: total_a = -1 (from update1) +? Actually node2 receives from update1? Update1 only affected node2? No update1 was on v=2, not covering node1. So node2 currently: from update1: total_a1 = -2, total_b1=7. From update2: total_a2 = -1, total_b2=3. So total_a = -3, total_b=10. depth[2]=1 => ans = -31+10=7. Check manually: update2: for node2 (descendant of 1 distance 1) adds x - k = 3-1=2. So node2 value becomes 5+2=7. Good.
So works.
Now need to ensure that depth[v] used in delta_b is correct: For v=1 depth=0, delta_b = x+0k = x. For v=2 depth=1, delta_b = x+1k.
Now consider update on node deeper than root.
Now think about potential pitfalls: The tree is rooted, but Euler tour must be based on children adjacency. Our DFS iterative with stack and exit markers is correct.
Now consider memory: children vector of vectors: total number of elements = n-1, about 3e5, fine.
Now implement.
Potential speed improvements: Use array of vectors? vector<vector> children(n+1); each vector may allocate separately. Acceptable.
Now final code.
But before finalizing, think about any overflow or negative mod in BIT.add: We computed delta_a as (-k) % MOD with if negative add MOD. That yields value in [0, MOD-1]. For delta_b we computed (x + depth[v]*k) % MOD, which is in [0, MOD-1]. For subtracting, we compute MOD - delta. If delta=0, MOD - 0 = MOD, and MOD % MOD = 0, so it's fine. However, if we directly pass (MOD - delta) to add, we should mod it because it could be MOD. So we can compute sub = (MOD - delta) % MOD. But (MOD - delta) is in [1, MOD] if delta>0; if delta=0, it's MOD, which mod MOD = 0. So we can compute sub = (MOD - delta) % MOD and pass. In code we pass (MOD - delta) and then in add we take val % MOD; val could be MOD, so mod becomes 0. That's fine.
Now test: delta=5, MOD - delta = MOD-5, add will take (MOD-5)%MOD? Actually add does val %= MOD; (MOD-5)%MOD = MOD-5, which is non-negative and less than MOD, good. For delta=0, MOD - 0 = MOD, MOD%MOD =0, good.
So we can simply pass MOD - delta without explicit mod, because add does mod anyway.
Now, however, note that delta may be negative? We ensure it's positive mod. So fine.
Now one more nuance: In BIT.add, we have while (idx <= n). But if idx=0? We never call with idx=0, because tin and tout start from 1.
Now finalize.
Now test with example given: Input:
3
1 1
3
1 1 2 1
2 1
2 2
Our code should output 2 and 1.
Now test with custom: n=1, queries: 1 1 100 50, then 2 1. Output should be 100. Let's compute: depth[1]=0, delta_a = -50 mod, delta_b = 100, range [1,1]. total_a = -50 mod, total_b=100. answer = -50*0+100=100. Good.
Now we can produce final answer.
Now consider large input: reading many numbers; use fast I/O.
Now final code in C++.
But there is a potential issue: Our BIT implementation uses long long and modulo inside add, which may be slower due to modulo operation inside while loop. But with 3e5 updates each performing O(log n) adds (about 19), total operations ~ 11 million, each with a modulo, that's fine. Alternatively, we could store values without modulo and only mod at query, but then values could exceed 64-bit? Possibly sum of up to 3e5 updates each adding up to 1e9+6, total 3e14, but multiplied by depth? No, BIT internal sums accumulate many values; each BIT index could get many updates: each update touches O(log n) BIT positions; number of updates q=3e5, each BIT position may be updated O(q * (some factor)). Actually each BIT node covers a range of indices, and each range update (l,r) touches O(log n) BIT nodes for each of the two point updates. So each BIT node may be updated many times. The worst-case cumulative sum for a BIT node could be as high as O(q * log n) * MOD? But each update adds a value at most MOD-1; if we don't mod during updates, the BIT node value could be up to q * log n * MOD. q=3e5, log n ~ 19, MOD ~ 1e9, product ~ 3e5191e9 = 5.7e15, still within 64-bit (9e18). So we could avoid mod inside BIT.add and only mod when returning sum. That would be faster. But to be safe, we can still mod inside; but it may be fine.
But note: In the BIT range update technique, we perform two point updates per coefficient. The values stored are delta (which are added to BIT nodes). The sum at a point is sum of contributions from all updates. If we store the deltas modulo MOD, the final sum mod MOD is correct. If we store raw integers (which may be negative) and then mod at query, we need to ensure the sum fits in 64-bit. Let's compute worst-case total_a sum: each update contributes -k (could be up to MOD-1). Number of updates covering a vertex could be up to q (if vertex is root). So sum of all -k_i could be up to q*(MOD-1) ~ 3e51e9 = 3e14, fits in 64-bit. So we could store raw in BIT (as long long) and mod at query. But we also have BIT internal nodes storing prefix sums of those deltas; they accumulate many contributions. However, the BIT sum operation aggregates values from O(log n) nodes, each node could have accumulated many deltas. The worst-case total for a BIT node might be larger: it covers a range of indices; each update that affects any index in that range will add its delta to that BIT node? Not exactly. The BIT point update (add value to an index) updates O(log n) BIT nodes, each node receives the same delta (not multiplied by number of indices). So each BIT node receives at most q deltas (each delta up to MOD-1). So max per node = q(MOD-1) ~ 3e14, still fits. Then prefix sum at an index sums up to O(log n) such nodes, total up to log n * 3e14 ~ 6e15, still fits. So we can store raw integers (long long) and only mod at final answer. That may be slightly faster and avoid modulo inside loops. But we also need to subtract (MOD - delta) for range end; that could be negative values. So we need to allow negative values in BIT. That's fine if we store raw. Then sum might become negative, but when we compute answer we take mod. However, we must be careful: In C++, negative mod can be tricky: (total % MOD + MOD) % MOD. But easier: use modulo addition. However, we can still store raw and at final answer compute (total_a % MOD + MOD) % MOD etc. But we need to ensure that total_a * depth[v] doesn't overflow 64-bit? total_a could be up to 3e14, times depth up to 3e5 gives 9e19, which exceeds 64-bit (~9e18). That's problematic: total_a could be 3e14, depth 3e5 product 9e19 > 2^63-1 (9.22e18). So it's possible to overflow 64-bit signed if we use raw sum without modulo. Example: q=3e5 all with k=1e9 (approx MOD) and all covering root, so total_a = -3e5*1e9 = -3e14 (absolute 3e14). depth[v] up to 3e5 => product absolute up to 9e19 > 9e18. So it might overflow signed 64-bit (max 9.22e18). So 9e19 > 9.22e18, so overflow is possible. So we cannot safely multiply raw total_a * depth without reduction modulo. Thus we need to reduce total_a modulo MOD before multiplication. So we must have total_a modulo MOD. That means we need to store values modulo MOD in BIT to keep numbers bounded, or compute total_a as raw but then take modulo before multiplication. But raw total_a might be huge, but we can take total_a % MOD. However, if BIT stores raw values, total_a = sum of raw deltas may be huge and we would need to compute total_a % MOD. But we could compute total_a = (sum over BIT nodes) and mod after each addition? Actually we can compute prefix sum raw (as long long) but it might overflow 64-bit if we don't mod? Let's check if prefix sum raw could overflow 64-bit. The raw sum at a point is sum of up to q deltas, each up to MOD-1, so max about 3e14, which fits in 64-bit (since 2^63-1 ~9.22e18). So total_a raw fits in 64-bit. Similarly total_b raw fits (3e14). So we can compute raw sum in BIT without modulo, returning a long long possibly up to 3e14, which fits. Then we can compute total_a_mod = ((total_a % MOD) + MOD) % MOD, and then multiply by depth (which is <= 3e5) mod MOD. However, total_a * depth may overflow before mod if we compute total_a * depth as raw product. That's why we need to mod total_a first or use modular multiplication. So we can do:
long long total_a_raw = bitA.sum(tin[v]);
long long total_a_mod = ((total_a_raw % MOD) + MOD) % MOD;
long long ans = (total_a_mod * depth[v] + total_b_mod) % MOD;
But total_a_raw could be negative? Since we store raw deltas (including negatives), sum may be negative. Taking % in C++ on negative yields negative remainder. So we adjust. That's okay.
But total_a_raw up to 3e14 fits, product total_a_mod*depth fits 64-bit? total_a_mod < MOD ~1e9, depth up to 3e5, product up to 3e14, fits. So that's safe.
Now total_b_raw also fits.
But we need to ensure BIT sum raw doesn't overflow 64-bit when accumulating contributions across many nodes? As reasoned, each node's contribution is at most 3e14, and sum of up to log n such nodes is also about 6e15 (since each node's value might be up to 3e14, and sum of about 19 such numbers could be up to 5.7e15, still within 9e18). So it's safe.
Thus we could store raw values in BIT without modulo, for speed. But modulo operations are not that heavy. However, careful about negative numbers: For range add, we add delta_a (could be negative) at l, and add -delta_a at r+1. So values can be negative. BIT will store them as long long. Then sum may be negative. In BIT sum, we accumulate as long long. That's fine. Then we compute mod.
But we have to be careful with modulo of negative numbers: We can compute ans = ((total_a_raw % MOD) * depth[v] + total_b_raw) % MOD; but in C++, total_a_raw % MOD may be negative, we then multiply by depth (positive), the product may be negative. Then add total_b_raw (could be negative). Then final % MOD could be negative, so we adjust: ans = (ans % MOD + MOD) % MOD. Or we can do:
long long ans = ( ( (total_a_raw % MOD + MOD) % MOD ) * depth[v] % MOD + (total_b_raw % MOD + MOD) % MOD ) % MOD;
But that's more operations.
Alternatively, store values modulo MOD in BIT and do all operations modulo MOD, thus we avoid negative issues and keep numbers small, and the multiplication total_a * depth[v] will be done with total_a in [0, MOD-1], which multiplied by depth (<=3e5) fits 64-bit, then mod. That's simpler and still efficient. Since we only do modulo on each BIT update (O(log n) times) and on each query (O(log n) sums). This is acceptable.
Given typical contest constraints, modulo operations are fine. We'll keep BIT storing modulo values.
But we need to ensure that negative delta_a mod correctly: we set delta_a = (-k) % MOD, and if negative we add MOD. That yields a value in [0, MOD-1]. Similarly, when we subtract at r+1 we add MOD - delta_a (which is also in [0, MOD-1]) because if delta_a = 0, MOD - 0 = MOD, but we then mod it (or BIT add will mod). So both are non-negative. So BIT will store only non-negative modded values. Then total_a and total_b are always in [0, MOD-1] (since sum of modded numbers mod MOD). That's fine. Then total_a * depth fits 64-bit. So we can avoid negative mod handling. So I'll keep BIT with modulo storage.
Thus code as earlier.
Now check for large n: Use int for depth, tin, tout. Use long long for BIT values to avoid overflow during intermediate addition? But we mod after each addition, so they stay within [0, MOD-1]. So we could use int for BIT if we mod each time? But MOD is 1e9+7, which fits in int (signed 32-bit? It's 1000000007, which is less than 2^31-1 (2147483647) so fits in signed int. However, when we add two such ints, sum may exceed 2^31, but still less than 2e9+14, which still fits in 32-bit signed? Actually 21e9+7 = 2000000014 < 2^31-1 (2147483647), so sum of two modded ints is at most 2MOD-2 = 2000000012, which fits in signed 32-bit. So we could use int. But we also multiply inside BIT add? No, only addition. So int is safe. However, to be safe with potential larger intermediate if we accidentally add many values before mod? But we mod each addition, so each tree node holds value < MOD. So int is ok. But many prefer long long for safety. We'll use long long.
Now implement final code.
But there's a catch: In BIT range add, we add delta_a at l and -delta_a at r+1. But we store modulo values, and we add (MOD - delta_a) at r+1 to subtract. However, we also may want to ensure that when we later query, we get the correct modulo sum. This works because the prefix sum mod MOD of the difference array yields the net delta at that point mod MOD. Example: Suppose we want to add val to range [l,r]. We do add(l, val), add(r+1, -val). Then prefix sum at i gives number of times val added minus times subtracted. If we use modulo arithmetic on both operations, we must ensure that -val mod MOD is represented as MOD - (val % MOD). Then prefix sum modulo MOD gives the correct net modulo. This holds because (a mod M) - (b mod M) mod M = (a - b) mod M. So it's consistent.
Now we should ensure that we use the same mod for both additions. So yes.
Now final code.
But before finalizing, think about possible integer overflow in depth[v]*k when computing delta_b. depth[v] up to 3e5, k up to MOD-1, product up to 3e14, fits in long long. So we compute: (1LL * depth[v] * k) % MOD.
Now code.
Now I'll produce final answer.
Edge Cases to verify:
-
n=1, q=0? Not possible q>=1.
-
Updates with large x and k, but we mod.
-
Many updates overlapping.
All good.
Now we can produce final solution.
Potential improvements: Could use fast I/O with scanf/printf. But cin with sync off is fine.
Now final code.
I'll write it with comments.
Now produce final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int MAXN = 300005;
int n;
vector<vector> children;
vector parent, depth, tin, tout;
// Fenwick tree for range add / point query (mod MOD)
struct BIT {
int n;
vector tree;
BIT(int n_) : n(n_), tree(n_ + 2, 0) {}
void add(int idx, long long val) {
val %= MOD;
if (val < 0) val += MOD;
while (idx <= n) {
tree[idx] = (tree[idx] + val) % MOD;
idx += idx & -idx;
}
}
long long sum(int idx) {
long long res = 0;
while (idx > 0) {
res = (res + tree[idx]) % MOD;
idx -= idx & -idx;
}
return res;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
children.resize(n + 1);
parent.resize(n + 1);
depth.resize(n + 1);
tin.resize(n + 1);
tout.resize(n + 1);
// read parents and build children lists
for (int i = 2; i <= n; ++i) {
cin >> parent[i];
children[parent[i]].push_back(i);
}
// compute depth (root = 1, depth 0)
depth[1] = 0;
for (int i = 2; i <= n; ++i) {
depth[i] = depth[parent[i]] + 1;
}
// Euler tour – iterative DFS with exit markers
stack<pair<int, bool>> st;
st.push({1, false});
int timer = 0;
while (!st.empty()) {
auto [u, isExit] = st.top();
st.pop();
if (!isExit) {
tin[u] = ++timer;
st.push({u, true}); // exit marker
// push children in reverse order to simulate recursive order
for (auto it = children[u].rbegin(); it != children[u].rend(); ++it) {
st.push({*it, false});
}
} else {
tout[u] = timer;
}
}
BIT bitA(n), bitB(n); // for coefficients of depth and constant
int q;
cin >> q;
while (q--) {
int type;
cin >> type;
if (type == 1) {
int v;
long long x, k;
cin >> v >> x >> k;
x %= MOD;
k %= MOD;
// coefficient for depth[u]
long long delta_a = (-k) % MOD;
if (delta_a < 0) delta_a += MOD;
// constant term
long long delta_b = (x + (1LL * depth[v] * k) % MOD) % MOD;
int l = tin[v], r = tout[v];
bitA.add(l, delta_a);
if (r + 1 <= n) bitA.add(r + 1, MOD - delta_a);
bitB.add(l, delta_b);
if (r + 1 <= n) bitB.add(r + 1, MOD - delta_b);
} else {
int v;
cin >> v;
long long total_a = bitA.sum(tin[v]);
long long total_b = bitB.sum(tin[v]);
long long ans = (total_a * depth[v] + total_b) % MOD;
cout << ans << '\n';
}
}
return 0;
}