We need to understand the Eulerian traversal order defined: it's essentially the order of vertices as they are first visited in a DFS from vertex 1, exploring neighbors in increasing order (by vertex number). Since vertices are labeled from 1 to n, but the DFS assigns id's according to the order of first visit. However, the input says: "You are given a weighted tree, the vertices of which were enumerated with integers from 1 to n using the algorithm described above." That means the given vertex numbers (the indices we use to refer to vertices) are exactly the order in which they are visited in this DFS. So the DFS started at vertex 1, and then recursively visited children. This imposes constraints on the tree: The parent of each vertex i > 1 must be a vertex with number less than i? In the input, each edge is given as p_i and w_i connecting vertex i (since i is from 2 to n) with p_i, and it's guaranteed that p_i < i. That's consistent with the DFS order: when doing DFS from 1, the parent of a vertex (the vertex from which it was first discovered) will have a smaller number than the child because it's visited earlier. But is it always that p_i < i? In DFS order, a vertex can be visited later but its parent could have a larger number? Typically DFS assigns increasing numbers in order of discovery, so the parent always has a smaller number. So the tree is rooted at 1 and edges are such that for each vertex i (2..n), its parent p_i is given with p_i < i. That's indeed a rooted tree. Also the DFS explores neighbors in increasing order, but since the neighbors' numbers are not necessarily in order? But the parent-child relationship is defined by the DFS: for any vertex v, its children are those neighbors that are unvisited when reached from v, and they are visited in increasing order of their vertex numbers. However, the vertex numbers themselves are the DFS order ids. That imposes constraints: For a vertex v, its children are those vertices u > v such that p_u = v? Actually, if p_i is given as parent (the first vertex that discovers i), then the children of a vertex v are the vertices i with p_i = v. But also there could be other neighbors (the parent) but that's it. So essentially we have a rooted tree with root 1, and edges oriented from parent to child. Since the DFS order (preorder) is exactly the vertex numbering, it means that for any subtree, the vertices are numbered consecutively? Not exactly: in a DFS preorder, the subtree of a node v consists of a contiguous interval of the preorder numbers, starting at v and ending after all its descendants. Indeed, in a rooted tree where children are visited in increasing order (by vertex number), the preorder numbers have the property that the subtree of v is a contiguous block [v, v + size(v) - 1]. Because when you assign numbers in preorder, you number v, then recursively number its children in order, then finish. Since the children are visited in increasing order of their numbers, but wait: The vertex numbers are assigned during DFS; they are not known in advance. The condition "neighbors of v in increasing order" refers to the actual vertex numbers (which are the final numbers). But at the time of DFS, we don't yet know the numbers of unvisited neighbors? However, the DFS algorithm enumerates vertices as it visits, assigning next_id. So when at vertex v, we consider its neighbors, which are other vertices that already have labels? No: In the problem statement, the tree is given with vertex numbers that are the result of this enumeration. So the numbers are fixed. So the DFS algorithm uses those numbers to decide the order: it goes through neighbors sorted by their index (the given numbers). So the order of visiting children is determined by the indices of neighbor vertices. This is consistent with the property that for any vertex v, its children (neighbors that are not its parent) will have indices greater than v? Possibly not: In a DFS preorder, when at v, you consider neighbors in increasing order; among them, the parent (if v != 1) is already visited, so you skip it. The children are those neighbors with larger indices? Actually, consider a vertex v. Its neighbors include its parent (which has smaller index, because parent is visited before child) and its children (which could have indices either larger or smaller? Since the DFS numbers are assigned in order of first visit, and you go from v to an unvisited neighbor u, you assign u the next number, which is greater than v because it's assigned after v and before any other unvisited vertices that may be visited later. So any child discovered from v will get a number greater than v. But what about neighbors that are not parent but have smaller indices? Could there be an edge from v to a vertex with a smaller index that is not its parent? If such an edge existed, then when DFS was at that smaller-index vertex earlier, it would have visited v as its child (since v would be unvisited). But the DFS started from 1; consider two vertices a and b with a < b, and there is an edge between them. The first time we encounter either vertex, the other is unvisited. Since we start at 1, the vertex with smaller number will be visited earlier (because numbers assigned in order of discovery). If a < b, then a was discovered before b. If there is an edge a-b, then when DFS was at a, it considered neighbors in increasing order; b is a neighbor with number b > a, so it would be visited from a (if b not visited yet) as a child, unless b had already been visited from some other vertex? But since a was visited before b, b is unvisited, so a would traverse to b and assign b the next number. So b becomes a child of a. Therefore, the edge direction is from the smaller-number vertex to the larger-number vertex. So indeed, for every edge (u,v) with u < v, u is the parent of v. The input format p_i < i confirms this: for vertex i, its parent is p_i. So the tree is rooted at 1, and the parent of each non-root is a vertex with smaller number. Thus the DFS order (preorder) coincides with the numbering. Moreover, the subtree of a vertex v is indeed a contiguous range: all vertices that are descendants (including v) have numbers in [v, v + size_subtree(v) - 1]. This is a standard property of DFS preorder when children are visited in some order (any order, but the numbers are assigned sequentially; the subtree forms a contiguous interval). So we have a rooted tree with known parent-child relationships and weights.
We need to answer queries: given v, l, r, find the minimum distance from v to any leaf whose index (i.e., vertex number) lies in [l, r]. The distance is the sum of edge weights along the unique path.
Constraints: n, q up to 500k. So need O((n+q) log n) or similar.
We need to efficiently compute min_{leaf u in [l,r]} dist(v, u). For each query, we need to consider leaf nodes in a range of indices.
We need to consider distances between arbitrary nodes and leaves.
Observation: distance(v, u) = depth(v) + depth(u) - 2depth(lca(v,u)), where depth is the sum of edge weights from root (node 1). So we need min over u in leaves ∩ [l,r] of (depth(v) + depth(u) - 2depth(lca(v,u))). Since depth(v) is constant for the query, we need min over u of (depth(u) - 2*depth(lca(v,u))). Or we could think of it as min_{u} (dist(v,u)).
We could precompute for each leaf some values, but queries involve arbitrary ranges of leaves by index.
Perhaps we can use segment tree or BIT over the leaf order (by index) storing some data structure that can combine distances? However distance depends on v, not just u. We could attempt to answer queries offline using techniques like "divide and conquer on tree" or "virtual tree" with segment tree of convex hull? Because distance formula is like: dist(v,u) = (depth(u)) + (depth(v) - 2*depth(lca)). But depth(lca) is not separable.
Alternatively, we could consider the concept of "closest leaf" queries on a static tree with range restrictions on leaf indices. This looks like a problem that can be solved using heavy-light decomposition (HLD) and segment tree storing for each segment of leaves something like a function of depth that can be combined with lca queries? Not trivial.
Another approach: Since the tree is given with DFS order numbering, leaves are some vertices. We can precompute for each vertex the distance to its nearest leaf (but that's independent of range). But we need restricted to index range.
Maybe we can answer queries using a data structure that supports range minima of a function f_v(u) = dist(v,u). For each query, we need min over u in a set S (leaves in [l,r]) of f_v(u). That's like a static array A (indexed by leaf order) where each leaf u has some associated value that depends on v. But the dependence is not linear.
We could possibly transform distance as: dist(v,u) = distance from v to u = depth(u) + depth(v) - 2depth(lca). For a fixed v, depth(v) is constant. So we need min_u (depth(u) - 2depth(lca(v,u))). Now lca(v,u) is some node on the path from root to v. So we could decompose the path from root to v and compute for each ancestor a the contribution if lca = a. For a node a on the path from root to v (including v), if the leaf u is in the subtree of a, and the child of a on the path to v is excluded? Actually, lca(v,u) = a if and only if u is in the subtree of a but not in the subtree of the child of a that is on the path to v (unless a=v, then u in subtree of v). More precisely, let a be a node on the path from root to v. For u, lca(v,u)=a if u is in the subtree of a, but not in the subtree of the child of a that is an ancestor of v (the next node down towards v). If a=v, then condition is u in subtree of v.
Then depth(u) - 2depth(a) = depth(u) - 2depth(a). For a given a, we need the minimum depth(u) over leaves u in the range [l,r] that are in the subtree of a but not in the subtree of the child that leads to v (if any). Then add constant depth(v) later.
So for a fixed v, we can consider each ancestor a (including v), and compute min over leaves u in range and in appropriate subtree of depth(u). Then answer = depth(v) + min_{a on path} (minLeafDepthInSubtreeExcludingChild - 2*depth(a)). Then the overall min is the answer.
Thus the problem reduces to: for many queries (v, [l,r]), we need to compute for each ancestor a of v, the minimum depth among leaves with indices in [l,r] that belong to a specific subtree (subtree of a, possibly excluding a certain child subtree). Then combine with -2*depth(a) and take minimum.
This suggests we can preprocess for each node a the set of leaves in its subtree, sorted by index (since indices are DFS order). Then we can query for a given a and range [l,r] the minimum depth among leaves in that subtree intersecting [l,r]. This is a 2D query: points (index, depth) where index is the leaf's id, and each leaf belongs to many ancestors? Actually each leaf belongs to all ancestors of that leaf. So we could potentially answer each query by considering the path from v up to root, performing a range minimum query on the leaf sets of each ancestor, constrained to index range [l,r]. Since depth of tree could be O(n), we cannot iterate over all ancestors per query.
But we could use heavy-light decomposition to break the path into O(log n) segments, and for each segment (which corresponds to a set of consecutive ancestors in the heavy path), we need to query the minimum leaf depth in the subtree of those nodes, but with the exclusion of a child subtree? Wait, for ancestors, the condition is that we consider leaves in subtree of a but not in the subtree of a specific child (the one on the path to v). This is like "subtree of a minus subtree of child c". This can be handled by taking two queries: min over leaves in subtree(a) minus min over leaves in subtree(child c). However, careful: we need min depth among leaves in (subtree(a) \ subtree(c)) ∩ [l,r]. That is min(min over subtree(a), min over subtree(c)? Actually, it's the minimum over leaves in subtree(a) intersect [l,r] that are not in subtree(c). If we compute min over subtree(a) and min over subtree(c), the global min might be from subtree(c) if it's smaller, but we need exclude those. So we need the minimum among leaves in subtree(a) that are not in subtree(c). That's not simply a combination of two independent minima; we need the second smallest? Actually, if we have two sets A = leaves in subtree(a) ∩ [l,r] and B = leaves in subtree(c) ∩ [l,r], we need min(A \ B). That could be either the min of A if that min is not in B, or the next min in A that is not in B. This is tricky.
Alternative: Since we are taking min over all ancestors, we could consider directly the leaf that gives the min distance. Possibly we can use a different perspective: For each leaf u, dist(v,u) can be expressed as something like: dist(v,u) = depth(v) + depth(u) - 2*depth(lca). If we fix u, then for a query with v, we need to know which v? So for a query, we need to examine leaves in range.
Maybe we can use an offline approach: sort queries by something and process using data structures. Since queries are up to 500k, we need something like O((n+q) log^2 n) maybe.
Another approach: Use centroid decomposition to answer distance queries with constraints on leaf indices? For each centroid, we could store for leaves in its subtrees their distances to centroid, and then answer queries by decomposing v to centroids and considering leaves in range. But the range constraint is on leaf indices, not on arbitrary nodes; we could augment with a segment tree on leaf indices for each centroid. However, there are O(n) centroids in decomposition, but each leaf appears in O(log n) centroid paths (i.e., in O(log n) layers). So total storage could be O(n log n) if we store for each centroid a sorted list or segment tree over leaf indices (by index) of min distance from centroid to leaf? Then for a query (v,l,r), we ascend the centroid tree from v's node to the root of centroid decomposition. For each centroid c on that path, we consider leaves in the subtree of the centroid that are not from the same child subtree as v? Actually, centroid decomposition typically handles queries of min distance from v to any point in a set with some property. Here the set is leaves in index range [l,r]. We could store for each centroid c a data structure keyed by leaf index that stores distance from c to that leaf. Then for query v, we consider each centroid c on the path from v to the root of centroid decomposition. For each c, the distance from v to a leaf u can be expressed as dist(v,c) + dist(c,u) if u is in a subtree of c that does not contain v (or if u is in the same component? Actually, in centroid decomposition, when we process centroid c, we remove c, and the remaining components are its children. For a leaf u, it belongs to exactly one child component of c (unless u=c, but c is not leaf because root 1 is not leaf but other centroids could be leaves? Possibly but we can handle). For v, we need to consider leaves u such that the path v-u passes through c. In centroid decomposition, the distance dist(v,u) = dist(v,c) + dist(c,u) if v and u are in different subtrees of c (or one of them is c itself). If u is in the same subtree of c as v (i.e., the component of c's child that contains v after removing c), then the path does not go through c; it would be handled at a deeper centroid (the next on the path). So for each centroid c on the path, we can query over leaves that are not in the same component as v (i.e., all leaves in the whole tree minus those in the component containing v) and also possibly c itself if it's a leaf? But we only consider leaves in index range [l,r]. So for each centroid c, we need to query the minimum of dist(v,c)+dist(c,u) over leaves u in [l,r] that are not in the component of c that contains v. That is dist(v,c) + min_{u in [l,r] and u in appropriate set} dist(c,u). So if we have for each centroid c a data structure that can answer: given a set of leaves (all leaves in the tree) minus those from a particular child subtree (which corresponds to the component containing v), find min dist(c,u) for u in [l,r]. This is essentially a range minimum query over leaf indices, but with an exclusion of a subtree. That's similar to the earlier issue.
We could avoid exclusion by storing for each centroid c and each of its child subtrees a separate data structure. Then for a given v, the relevant leaves are those in all other subtrees plus possibly c itself. Then we could take the minimum over these data structures (each covering a subset of leaves). So we would need to query each such data structure for the minimum dist(c,u) over u in [l,r] and then add dist(v,c) and take min. If there are many children, this could be large. However, in centroid decomposition, each node has degree that can be large, but over all centroids, the total number of child subtrees is O(n) (since each edge is considered in O(log n) levels, but each centroid may have many children). But if we have to query all other children for each centroid on the path, the total per query could be O(log n * degree(c)), which could be O(n) in worst case (e.g., star). That's not acceptable.
We need a more efficient method.
Consider the DFS order property: leaves are vertices with no children. The indices are in preorder. So leaves appear in order.
The distance query can be thought of as: For a given v, we want the leaf u in [l,r] minimizing dist(v,u). Since the tree is static, perhaps we can precompute for each vertex the nearest leaf (overall) but we need range.
We could use segment tree over the leaf order (by index) storing a data structure that can answer for a given v the min distance to any leaf in the segment. That data structure per segment could be something like: we store a set of leaves, and we need to support query: given v, min_{u in set} dist(v,u). That's exactly the "point set to point distance" query on a tree. There are known techniques: if we precompute LCA and depth, then distance is depth(v)+depth(u)-2*depth(lca). For a fixed set S, we could precompute the leaf with minimal depth? Not exactly because of lca term.
For a static set S (e.g., the set of leaves in a segment), we could answer min dist(v,S) quickly if we have preprocessed something like the virtual tree of S? But per query we have different v and different segment. So we need a data structure that can combine sets quickly, like segment tree where each node stores some structure that can answer min distance to any point in its set. Then for query [l,r] we combine O(log n) nodes, each returning a candidate distance, and take min. The question: what structure to store per node to answer min distance to arbitrary v in O(log n) or O(1) time? If per node we can answer in O(log n) time, total query would be O(log^2 n), which may be acceptable (500k * log^2 ~ 500k * 400 = 200M maybe borderline but possibly okay in C++ with optimization). But we need to consider memory: each node stores something about its set of leaves. The total number of leaves is up to n. Storing full set per node would be O(n log n) memory, which for n=500k could be ~10 million, maybe okay. But the structure for distance queries: for a set of nodes on a tree, the minimum distance to a query node v can be found by considering the node in the set that is "closest". There is a technique using LCA and precomputed depths: For a set S, define its "virtual tree" and maybe store the node with minimal (depth(u) - 2*depth(lca(v,u)))? Not linear.
But there is known approach: For a static tree, to answer min distance from a query point to a set of points, you can use the concept of "centroid decomposition" on the set? However, here the set S varies per segment node, and there are many such sets. Building a data structure per segment node from scratch would be heavy.
Alternatively, we could use "divide and conquer on queries" or "offline processing" using segment tree over leaf indices and process queries by traversing the segment tree: For each node of the segment tree (covering a range of leaves), we consider all queries that cover that range, and we compute something for those queries using a data structure that can answer min distance from any v to any leaf in that node's set? Actually we could process queries offline by adding leaves one by one in index order and using a data structure that maintains, for each vertex v, the minimum distance to any leaf added so far. Then for queries of type (v, l, r), we could answer as: min distance to leaves with index ≤ r minus something? But we need both l and r. Classic offline approach: sort queries by r, process leaves in increasing index, maintain a structure that for each vertex v stores current min distance to any leaf seen so far, then for a query (v, l, r) we need min over leaves with index between l and r, not just ≤ r. That's a range query over time; we could use a segment tree over indices where we store for each leaf its effect, and for queries we need min over [l,r] of dist(v, leaf). But dist(v, leaf) depends on both v and leaf; not a simple value.
We could use the concept of "persistent segment tree" keyed by leaf index, storing for each leaf something, and for a given v we need to combine? Not obvious.
Maybe we can use "Euler tour tree + segment tree" with something like: For each vertex v, we can compute for all leaves u, dist(v,u). But we cannot store all pairs.
Another angle: Since the DFS order corresponds to subtree intervals, the leaves in a range [l,r] may not form a contiguous subtree; they are scattered across the tree. However, the query asks for leaves with indices in that range. The indices are preorder numbers. Leaves have preorder numbers. So the range [l,r] is a contiguous segment of the preorder list, but not necessarily a subtree (it's a set of vertices that are interleaved across different subtrees). However, we can decompose [l,r] into O(log n) disjoint subtrees? Actually, we can represent any interval of the Euler tour (preorder) as a union of O(log n) subtrees using a segment tree over the indices where each node corresponds to a contiguous range of indices; but that range may not correspond to a full subtree unless the range aligns with subtree boundaries. But we could still use a segment tree over the leaf indices (which are a subset of all indices) and each leaf of the segment tree corresponds to a leaf in the tree. The leaves in the segment tree are the actual leaf vertices. So the internal nodes of the segment tree correspond to intervals of leaf indices. Then for each such interval (a set of leaves), we need to quickly answer min distance to a query vertex v. That's exactly what we considered.
Now, what structure can answer min distance to a set of nodes on a tree quickly? There is a known technique: For a set S, the minimum distance from a query node v to any node in S can be computed as min_{u in S} (depth(u) + depth(v) - 2depth(lca(v,u))). This can be transformed as depth(v) + min_{u in S} (depth(u) - 2depth(lca(v,u))). The term depth(u) - 2*depth(lca(v,u)) can be computed using the concept of "virtual tree" or "auxiliary tree" with DP. But we need a fast per query mechanism.
Alternatively, we can use the "closest point problem" on trees using LCA and binary lifting with precomputed minima per ancestor? If we precompute for each node v, the minimum distance to any leaf in a given set? But the set changes per query.
Maybe we can use a segment tree where each node stores the "diameter" of its set? For distance queries to a set, the minimum distance to a set is not directly the diameter. But there is a known technique: For a set of nodes S, the distance from v to the closest node in S can be computed if we maintain for each node the two farthest nodes? Not.
Wait: There is a known trick: For a set S, the function f(v) = min_{u in S} dist(v,u) can be expressed as: min_{u in S} (depth(v) + depth(u) - 2depth(lca(v,u))) = depth(v) + min_{u in S} (depth(u) - 2depth(lca(v,u))). If we precompute for each node x, the minimum of depth(u) among u in S that are in the subtree of x, and also possibly other info. Actually, consider the LCA: For a fixed v, lca(v,u) is some ancestor of v (or v itself). So f(v) = depth(v) + min_{a on path from root to v} ( min_{u in S, lca(v,u)=a} (depth(u) - 2depth(a)) ). And the condition lca(v,u)=a means u is in the subtree of a but not in the subtree of the child of a that is ancestor of v (call that child w). So if we define for each node a, let best[a] = min_{u in S ∩ subtree(a)} depth(u). Then for a given v, the candidate for ancestor a (with child w) would be min over u in S ∩ (subtree(a) \ subtree(w)) of depth(u) - 2depth(a). This is essentially min( best_in_subtree_a_excluding_child_w ) - 2*depth(a). If we had for each node a, the best depth among S in its whole subtree, and also for each child of a, the best depth among S in that child's subtree, then for a given v we could, for each ancestor a, compute min excluding that child as either best[a] if the min leaf is not from that child, or we need the second best? Actually, if the minimum depth leaf in subtree(a) lies in child w, then the best excluding w would be the second best among the children (or possibly from a itself if a is in S). So to answer quickly, we need for each node a, the minimum depth leaf in its subtree, and also for each child, the minimum depth leaf in that child's subtree, and maybe the second minimum overall. However, this would need per-node data that depends on S. Since S is the set of leaves in the query range, which varies, we cannot precompute per node for all possible S.
But we are considering segment tree nodes: each node corresponds to a fixed set of leaves (some subset). For that fixed set, we could precompute something like: For each node a in the tree, store the minimum depth leaf in that set that lies in the subtree of a. Then for query v, we can walk up from v to root and compute the answer using those per-node minima, in O(depth) which could be O(n). But we can accelerate using binary lifting: For each node a, we know minDepthSubtree[a] = min_{u in S ∩ subtree(a)} depth(u). Then for a query v, we can compute answer as depth(v) + min_{a on path root->v} (minDepthSubtree[a] - 2depth(a)). But note that this formula gives the minimum over all u in S, regardless of the exclusion condition? Let's verify: Suppose we take a on path. For u in S, lca(v,u) is some ancestor a. If we consider the expression min_{a} (min_{u: u in S, lca(v,u) = a} (depth(u) - 2depth(a))) = min_{a} ( min_{u in S ∩ subtree(a) \ subtree(child)} depth(u) - 2depth(a) ). However, if we use minDepthSubtree[a] (which includes all u in subtree(a)), it might give a u that is actually in subtree(child) and thus lca(v,u) would be deeper than a, not a. But would using minDepthSubtree[a] possibly yield a smaller value for the expression depth(u)-2depth(a) than the true min for that a? Actually, for a fixed a, consider a leaf u in subtree(child) where child is on the path to v. Then lca(v,u) is actually deeper than a (some descendant of a along the path). So if we mistakenly consider that u under a, we would be using depth(u)-2depth(a) but the true distance from v to u would be depth(v)+depth(u)-2depth(lca) where lca is deeper, so depth(u)-2depth(lca) would be larger (since subtracting larger depth). Actually depth(u)-2depth(a) is smaller than depth(u)-2depth(lca) because depth(a) < depth(lca). So using minDepthSubtree[a] could underestimate the distance (i.e., give a value smaller than the true distance for that u) because it would assume lca = a, but actual lca is deeper, making distance larger. So the formula min_{a} (minDepthSubtree[a] - 2depth(a)) could be less than the true min distance (since for a leaf u that is in subtree(child), the correct contribution would be at some descendant a' (the actual lca) with -2depth(a') which is more negative? Actually let's compute: For leaf u, the distance from v is depth(v)+depth(u)-2depth(lca(v,u)). For that leaf, if we consider an ancestor a above lca, the expression depth(u)-2depth(a) is less than depth(u)-2depth(lca) because depth(a) < depth(lca) => -2depth(a) > -2depth(lca), so depth(u)-2depth(a) > depth(u)-2depth(lca)? Wait: since depth(a) is smaller, -2depth(a) is larger (less negative) than -2depth(lca). So depth(u)-2depth(a) > depth(u)-2depth(lca). For example, depth(a)=0, depth(lca)=5, then -20=0, -25=-10, so depth(u)-2depth(a) is larger (less negative). So depth(u)-2depth(a) is actually larger? Let's compute numerically: depth(u)=20, depth(lca)=5 => distance = depth(v)+20-10 = depth(v)+10. For a=root depth 0, depth(u)-2depth(a)) would be attained at the true lca (or deeper) because deeper a gives more subtraction. So if we include all leaves in subtree(a) even those that have lca deeper, the expression (depth(u)-2depth(a)) is actually equal to the true min distance? Let's examine: For each leaf u, its contribution to the min over a is min_{a is ancestor of u and ancestor of v? Actually the expression we minimize over a is depth(u)-2*depth(a) for a that are ancestors of both v and u? But if we take a arbitrary on path from root to v, not necessarily ancestor of u? For the expression to be meaningful, we need u to be in subtree(a). But if u is not in subtree(a), then we cannot consider that pair. So for a given u, the set of a such that u ∈ subtree(a) are exactly the ancestors of u (including u). Also we require that a is on the path from root to v? But we are minimizing over all a on path root->v. For a particular u, some of these a may not be ancestors of u (i.e., u not in subtree(a)). Only the ancestors that are common to v and u (i.e., up to lca) will have u in subtree(a). Actually, if a is an ancestor of v and also an ancestor of u, then u is in subtree(a). So the common ancestors are those up to lca(v,u). For a above lca, they are also ancestors of u. So for leaf u, the values considered for a on the path from root to v are:
- For a from root to lca(v,u) inclusive: u ∈ subtree(a). For each such a, expression = depth(u)-2*depth(a).
- For a below lca (i.e., between lca(child) and v): u not in subtree(a), so not considered.
Thus the minimum over a on path of (depth(u)-2depth(a) for a where u in subtree(a)) is actually achieved at the deepest such a, i.e., at a = lca(v,u), because depth(u)-2depth(a) decreases as depth(a) increases (since -2depth(a) becomes more negative). So for a given u, the minimal value over a is depth(u)-2depth(lca). Therefore, if we define for each node a the value minDepthSubtree[a] = min_{u in S ∩ subtree(a)} depth(u), then for a given v, consider the values over a on path: M(a) = minDepthSubtree[a] - 2depth(a). Then min_{a} M(a) = min_{a} min_{u in S ∩ subtree(a)} (depth(u)-2depth(a)). For each u, its contribution appears in M(a) for all a that are ancestors of u up to lca? Actually, for u, it contributes to M(a) for all a that are ancestors of u and also ancestors of v (since a on path from root to v). The min over those a of (depth(u)-2depth(a)) is achieved at the deepest common ancestor, i.e., lca. So for each u, there exists an a (=lca) where M(a) ≤ depth(u)-2depth(lca) (actually equality if u is the leaf achieving minDepthSubtree[a] for that a? Not necessarily. minDepthSubtree[a] might be a different leaf u' that gives even smaller value. So min_{a} M(a) = min_{u in S} (depth(u)-2depth(lca(v,u)))? Let's verify: For any u, let a = lca(v,u). Then u ∈ subtree(a), so minDepthSubtree[a] ≤ depth(u). Thus M(a) = minDepthSubtree[a] - 2depth(a) ≤ depth(u) - 2depth(a). So the minimum over a of M(a) is at most the minimum over u of distance component. Conversely, for any a, let u_a be the leaf in S ∩ subtree(a) achieving minDepthSubtree[a]. Then for that leaf, lca(v,u_a) is some node b on the path from root to v that is ancestor of both; note that b is at least as deep as a? Actually, if u_a is in subtree(a), then lca(v,u_a) could be deeper than a if the leaf is also in the subtree of the child of a that is on the path to v. In that case, b is deeper. So distance for u_a is depth(u_a)-2depth(b) which is ≤ depth(u_a)-2depth(a) because depth(b)≥depth(a) => -2depth(b) ≤ -2depth(a). So depth(u_a)-2depth(b) ≤ depth(u_a)-2depth(a) = M(a). Therefore, for each a, the true minimum distance (over S) is at most the distance for u_a, which is ≤ M(a). Actually we have: true_min_distance_component = min_{u in S} (depth(u)-2depth(lca(v,u))) ≤ depth(u_a)-2depth(lca(v,u_a)) ≤ depth(u_a)-2depth(a) = M(a). So true_min ≤ M(a) for all a. Then min_{a} M(a) is an upper bound on true min? Wait, we have true_min ≤ each M(a). So true_min ≤ min_a M(a). But we also have true_min ≤ min_a M(a). But we want equality? Actually we want the true min. If true_min is less than or equal to min_a M(a), it could be strictly less. Consider a scenario: S contains two leaves, one deep in subtree of a child not on path, and one shallower in subtree of that child on path. Let's test: Tree: root(1) depth 0, child 2 depth 10, leaf u1 at depth 20 under child 2 (which is on path to v? Let's set v is in child 2 subtree, so path root->v includes root and 2 and maybe deeper). S includes leaf u2 in another child 3 of root depth 5 (so depth(u2)=5). v is under 2. Then true min distance: For u1, lca is 2, distance = depth(v)+20-2depth(lca)) = depth(v)+0. So it works. But what if minDepthSubtree[2] is achieved by u1 which is in the child on path, then M(2)=0, and true min also 0. So seems min_a M(a) gives exactly min_{u in S} (depth(u)-2depth(a) ≤ depth(u) - 2depth(lca)). So min_a M(a) ≤ true_min_component. Conversely, for each a, let u_a be argmin depth in subtree(a). Then true_min_component ≤ depth(u_a)-2depth(b) ≤ depth(u_a)-2*depth(a) = M(a). So true_min_component ≤ M(a) for all a. Hence true_min_component ≤ min_a M(a). Combine both inequalities: true_min_component = min_a M(a). Great! So we have:
Let for any set S of leaves, define for each node x: bestDepth[x] = min_{u in S ∩ subtree(x)} depth(u) (or +∞ if none). Then for any vertex v, we have:
min_{u in S} dist(v,u) = depth(v) + min_{a on path from root to v} (bestDepth[a] - 2*depth(a))
Because the minimum over a on the root-to-v path of (bestDepth[a] - 2depth(a)) equals the min over u in S of (depth(u)-2depth(lca(v,u))). That's a neat simplification.
Thus the problem reduces to: We need to answer queries (v, l, r) where S is the set of leaves with indices in [l,r]. For each such query, we need to compute:
ans = depth(v) + min_{a ∈ ancestors(v) ∪ {v}} ( bestDepth[a] - 2*depth(a) ), where bestDepth[a] = minimum depth among leaves in S that are in the subtree of a.
(Note: root is ancestor.)
Thus we need a data structure that can quickly compute, for a given set S defined by leaf index range [l,r], the value F(v) = min_{a on path root->v} ( bestDepth[a] - 2*depth(a) ).
Now bestDepth[a] depends on S (range of leaves). So we need to support queries that, given a path root->v and a range of leaves, compute the minimum over nodes a on that path of ( bestDepth_in_range[a] - 2*depth(a) ), where bestDepth_in_range[a] = min depth of leaf in subtree(a) with index in [l,r].
We can precompute depth for all nodes.
Now we need a way to answer many such queries efficiently.
We can think of building a segment tree over the leaf indices. For each segment tree node (covering a contiguous range of leaf indices), we precompute for all nodes a in the tree the value bestDepth_in_this_segment[a] (the minimum depth of leaf in that segment that lies in subtree(a)). Then for a query covering a range that can be decomposed into O(log n) segment nodes, we need to combine the bestDepth information from those nodes to compute the min over path. Since the query's S is the union of the leaves in those segment nodes, the bestDepth for the union is the min over the segment nodes' bestDepth values. That is, for a node a, bestDepth_total[a] = min over the segments (bestDepth_seg[a]). Then we need to compute min_{a on path} (bestDepth_total[a] - 2depth(a)). If we could, for each segment node, compute a function that maps a path to a value, and combine them via min, maybe we can do something like: For each segment node, we precompute an array or a data structure that allows us to query, for any v, the minimum over ancestors a of (bestDepth_seg[a] - 2depth(a)). Then for the union of segments, the answer would be the minimum over those segment nodes of their per-segment query results? Not exactly, because we need min over a of (min_seg bestDepth_seg[a] - 2depth(a)). That is not equal to min over seg of (min over a of (bestDepth_seg[a] - 2depth(a))) because the minimum over a after taking min over seg is the same as min over a ( min_{seg} bestDepth_seg[a] - 2depth(a) ) = min_{a} ( min_{seg} (bestDepth_seg[a] - 2depth(a)) ) = min_{seg} min_{a} (bestDepth_seg[a] - 2*depth(a))? No, careful: min_{a} ( min_{seg} f_seg(a) ) is not necessarily equal to min_{seg} min_{a} f_seg(a) because the a that achieves the min may differ per seg. But we need min_{a} ( min_{seg} f_seg(a) ). This is the minimum over all a of the per-segment minima at that a. This is equal to the minimum over all pairs (seg, a) of f_seg(a). So indeed:
min_{a} ( min_{seg∈cover} bestDepth_seg[a] - 2depth(a) ) = min_{seg∈cover} min_{a} ( bestDepth_seg[a] - 2depth(a) )
because we are taking min over all a and all seg. So the overall value we need is the minimum over the covering segments of ( min_{a on path} (bestDepth_seg[a] - 2*depth(a)) ). This is true because:
Let g(a) = min_{seg} f_seg(a). Then min_a g(a) = min_{a} min_{seg} f_seg(a) = min_{seg} min_{a} f_seg(a). Yes, because min over a of (min over seg f_seg(a)) = min over (a, seg) f_seg(a) = min over seg (min over a f_seg(a)). So indeed we can compute for each segment node a value H(seg, v) = min_{a on path root->v} ( bestDepth_seg[a] - 2*depth(a) ). Then for a query covering a set of segments, the answer = depth(v) + min_{seg in cover} H(seg, v). Great!
Therefore, we can build a segment tree over the leaf indices (by their order). For each segment tree node (covering a contiguous range of leaf indices), we precompute for all vertices? Actually, H(seg, v) depends on v. We need to be able to query H(seg, v) quickly for any v. So per segment node, we need a data structure that, given v, returns min over ancestors a of (bestDepth_seg[a] - 2depth(a)). Since bestDepth_seg[a] is precomputed per node a for that segment, we can compute for each a the value val_seg[a] = bestDepth_seg[a] - 2depth(a). Then H(seg, v) = min_{a on path root->v} val_seg[a]. That's a classic query: minimum value on a path from root to v (ancestors). That can be answered quickly using preprocessing like binary lifting with RMQ on tree (e.g., sparse table for ancestors). Since the tree is static, we can precompute for each node its ancestors and store the minimum val along the path using binary lifting. But val_seg depends on the segment node, so we cannot precompute for all segments separately because there are O(n) segment tree nodes (about 4n). For each segment node we would need to store val for each of the n vertices, leading to O(n^2) memory. Not feasible.
We need a more clever way.
But note: bestDepth_seg[a] is defined as the minimum depth of any leaf in the segment that lies in subtree(a). For a fixed segment node (covering a set of leaves), this is a function over the tree. Could we compute H(seg, v) efficiently without storing per-node values? Possibly we can compute it on the fly using a data structure that can answer path minima of a function that is defined as bestDepth(segment) - 2depth. However, bestDepth(segment)[a] is essentially the minimum over leaves in the segment that are in subtree(a) of depth(leaf). This resembles a "subtree minimum query" for a dynamic set of leaves (the segment). For a fixed set of leaves (segment), we can precompute something like a virtual tree or use a data structure that can answer queries of the form: given v, what is the minimum (depth(leaf) - 2depth(lca(leaf, v)))? Wait we already reduced to min over ancestors. But perhaps we can answer directly using a segment tree on the Euler tour with some values? Let's think differently.
Alternative: Instead of building a segment tree over leaf indices, we could answer queries offline using a divide-and-conquer on the tree (like DSU on tree or something). But we need to handle range queries on leaf indices.
Observation: Leaf indices are just indices. The tree's DFS order gives a natural mapping of leaves to indices. The range [l,r] is an interval in the preorder. Could we use a segment tree over the original vertex indices (preorder) to answer queries of the form: given v and interval, find min distance to any leaf in that interval? The function dist(v, leaf) can be expressed as depth(v) + depth(leaf) - 2*depth(lca). If we could maintain for each node a data structure over leaves in its segment... Not sure.
Maybe we can use a "range minimum query" structure over the leaf order where each leaf stores some value that depends on v, but v varies. The typical trick for many distance queries on tree with point sets is to use the fact that dist(v,u) = depth(v) + depth(u) - 2depth(lca(v,u)). If we fix v, depth(v) is constant; we need min over u in set of (depth(u) - 2depth(lca(v,u))). The term depth(u) is fixed per u, but depth(lca(v,u)) depends on v and u. However, we can think of processing queries offline sorted by v? But each query has its own v.
Another approach: Use centroid decomposition to answer each query by binary searching? Not.
Let's revisit the earlier reduction: We have to compute min over a on path root->v of (bestDepth[a] - 2*depth(a)), where bestDepth[a] = min depth of leaf in S that lies in subtree(a). So the value at each ancestor a is essentially the minimum depth among leaves in the intersection of S and subtree(a). This looks like we could answer using a data structure that supports: given S (as a range of leaf indices), for each node a on path from root to v, we need to compute that minimum. But note that bestDepth[a] for different a are not independent; they are based on the same set S.
Could we answer this by walking up from v to root and at each step we need to know the minimum depth leaf in S that lies in the current subtree? If we could answer such subtree minimum queries for the given S efficiently, and since the path length could be O(n), we need to accelerate.
We can use binary lifting with precomputed data about leaves? For example, for each node a, we could store the list of leaves in its subtree sorted by depth? Not efficient for dynamic S.
But maybe we can use a segment tree over the leaf indices, and for each query we will walk up the tree but use the segment tree to answer "minimum depth leaf in subtree(a) with index in [l,r]". That is: for each ancestor a, we can query the segment tree for the minimum depth leaf in the intersection of [l,r] and subtree(a). Subtree(a) corresponds to a contiguous range in the DFS order (since it's preorder). Indeed, subtree of a is an interval [a, a + size(a) - 1] in terms of vertex indices. However, our leaves are a subset of vertices. So the set of leaves in subtree(a) with indices in [l,r] is: leaves whose index is in [l,r] and also whose vertex number (which is the DFS index) is in [a, a+size(a)-1]. So it's a 2D range query: we have leaves each with two coordinates: their index (which is the same as their DFS number) and they are also identified by that number. Actually, each leaf has a single index (its vertex number). The condition "index in [l,r]" is one interval, and "vertex in subtree(a)" is another interval on the same linear order (since vertex numbers are DFS order). So the intersection is simply the leaves whose index lies in the intersection of two intervals: [l,r] ∩ [a, a+size(a)-1]. So it's just a 1D range query on an array of leaves: we need the minimum depth among leaves whose indices are in a certain interval I = [l,r] ∩ [a, a+size(a)-1]. So we can precompute an array over