We need to parse problem description carefully. It describes a game with water and coins, aiming to maximize dollars won (max over moves of water at root after each move). The player initially has k liters total to pour into tanks (any vertices except root) and p coins. Then moves are performed until no water remains. At each move:
-
First, "Mashmokh opens doors of all tanks. Then Mashmokh closes doors of some tanks (he is not allowed to close door of tank in the root) for the duration of this move." So at start of each move, all doors are open; then he chooses a subset of non-root vertices to close for this move. For each closed tank, if it contains w liters, he pays w coins? Actually: "Let's denote the number of liters in some tank with closed door as w, Mashmokh pays w coins for the closing of that tank during this move." So he pays w coins for each closed tank, where w is the amount of water in that tank at the moment when he closes the door? Or after the move? It says "for the duration of this move" and "the number of liters in some tank with closed door as w, Mashmokh pays w coins for the closing of that tank during this move." So at the time of closing, the tank contains w liters. He pays w coins. So his total coin expenditure per move equals sum of water amounts in the tanks he closes.
-
Then, process vertices in order of non-decreasing depth (i.e., from root downwards? Actually sorted by depth, nondecreasing. So root depth 0 first, then vertices at depth 1, etc). For each vertex xi in that order:
- If xi is root, its tank is emptied. (i.e., all water from root tank is removed? It says "Firstly vertex x1 (which is the root itself) is emptied." That means we take water from root tank and discard it? The game ends when no water remains, so perhaps the water removed from root is effectively the dollars we win? Actually the dollar amount we win is max(w1, w2, ..., wl) where wi is the amount of water inside the tank of the root after the i-th move. So after each move, after the process (emptying root and moving water), we consider the water that ended up in root after the move? But note: they said "after the i-th move", and the process description says that during the move, we first empty root. But that seems contradictory: if we empty root at beginning of the move, then after the move there could be water in root because water moved from children? Let's read carefully:
"The vertices from this list should be considered one by one in the order. Firstly vertex x1 (which is the root itself) is emptied. Then for each vertex xi (i > 1), if its door is closed then skip the vertex else move all the water from the tank of vertex xi to the tank of its father (even if the tank of the father is closed)."
So the steps: For each vertex in order of increasing depth, we process:
-
For root: we empty it. So any water that was in the root before this move is removed, not counted in wi? But wi is the amount of water inside the tank of the root after the i-th move. So after processing all vertices, the root may have received water from its children, because after the root is emptied, later when processing its children, if those children are not closed, they will move their water to the father (root). So the water from children is moved to root after root was emptied. That means after the entire move, the root contains water that came from its descendants that were not closed, but not water that was originally in root. So wi is the amount that ended up in root after all transfers.
-
Then for each other vertex: if its door is closed, we skip it (i.e., do nothing, so its water stays in that tank? Actually it says "skip the vertex else move all the water from the tank of vertex xi to the tank of its father." If closed, we don't move the water. So that water remains in that tank for the next move? The move is defined as the whole sequence of processing all vertices. At the end of the move, we check if there is any water left anywhere. If yes, repeat. But note: After the root is emptied, we process children. For a child with door closed, we don't move its water; that water stays in that child's tank. So it remains for the next move. For a child not closed, we move all its water to its father. However, what about the father's door? It says "even if the tank of the father is closed." So we can move water into a closed tank; that's allowed. But the closed tank's door being closed prevents water from being moved out of it? Actually the rule only says: if the door of the tank is closed, we skip moving water from it (i.e., it's not allowed to be taken from). But it can receive water. So closed tank can be filled by its children moving water into it. However, since it's closed, in the same move, its water is not moved upward (since it will be processed later when its turn comes? But recall processing order: vertices are processed in increasing depth. So a closed tank (non-root) will be processed at some step after its ancestors. At its turn, since its door is closed, we skip it, so its water stays. But earlier, when its children (descendants deeper) are processed, they might move water into it if they are not closed. So that's fine.
-
Also important: When a vertex is processed and it's not root and its door is not closed, we move ALL its water to its father. So after that, its tank becomes empty (unless later some of its descendants move water into it? But descendants are deeper and will be processed later, as order is increasing depth. So after moving water from a vertex to its father, later its children (deeper) will be processed. They will try to move water to it, but by then its tank is empty? Actually they move water to its father, which is this vertex. So if we already moved this vertex's water to its father, then later its children will move water into this vertex. That water will be added to the tank. But then after that, will there be any step later that moves that water upward? Since processing order is increasing depth, once we have processed a vertex, we won't come back to it. So water added to a vertex after its turn will remain in that tank until the next move. That's important.
Thus each move consists of:
- Choose some non-root vertices to close (paying their water amount in coins).
- Then traverse vertices from root outwards (i.e., BFS/level order). For each vertex:
- If root: empty its tank (remove water).
- Else if door closed: do nothing (water stays).
- Else: move all its current water to its parent. (Its tank becomes empty, unless later children add water.)
But note: When we move water to parent, the parent might be closed or not, but we still add water. If parent has already been processed (since we go from shallow to deep), then the parent won't get processed again this move, so that water will stay in parent for this move. But if parent is deeper (i.e., child is shallower? No, parent is always shallower, so parent is processed earlier. So when we move water from a vertex to its parent, the parent was already processed earlier in the order. So the water moved to parent will not be moved further upward in this move, because the parent's turn has already passed. That means water moved from a vertex goes to its parent and remains there until the next move (unless parent is root, but root was emptied at start of move, but that happened before any children moved water? Actually root is processed first: we empty root. Then later children move water to root. So that water ends up in root after the move, and since root was emptied, it is essentially the net accumulation from children. But root will not be processed again this move; so water in root at end of move is what we get.)
Thus the effect of a move is:
- All water in root is removed.
- For each vertex v (non-root) that is NOT closed, all water that was in v at start of the move is transferred to its parent (and stays in parent for the remainder of this move, but not moved further this move). Additionally, any water that was in closed vertices remains in place.
- Additionally, water that gets transferred from a child to a closed parent is allowed, but the closed parent retains that water (since its door is closed, it won't be moved out this move, but it could receive water from children). So closed vertices can accumulate water from their non-closed children.
- However, note that when a child is not closed, it moves all its water to parent. But that water might then be moved upward in later moves.
Therefore the process is like: each move, we can choose a set of vertices to "block" from sending water upward, paying a cost equal to the water they hold at that moment. Then water flows upward one level from all unblocked vertices. The water that reaches root is removed from the system (counted as root water after the move? Actually it is not removed; it is in root at end of move, but then after the move we check for termination; if there's water anywhere else, we repeat. The water in root is not removed until the next move's first step, where root is emptied. So at the end of each move, the root has some water (the sum of water that moved from its children that were unblocked, plus maybe from deeper). That amount is wi. The game ends when no water remains in any tank, i.e., after some move the root and all others are empty.
Goal: Initially we can pour up to k liters into any non-root vertices (each gets integer? Probably at most 1 liter per tank? Wait: "Mashmokh chooses some (no more than k) of these tanks (except the root) and pours into each of them exactly 1 liter of water." That means each chosen tank gets exactly 1 liter, and he can choose at most k tanks? Actually "no more than k" suggests he can pour at most k liters total, but also each chosen tank gets exactly 1 liter. So the initial distribution is: a set S of non-root vertices, with each vertex receiving exactly 1 liter; total |S| ≤ k. So initial water amounts are either 0 or 1 per vertex (except root initially 0). So it's a binary distribution.
We have p coins to spend on closing doors during moves. The cost per move is sum of water amounts in the vertices we choose to close. We can close doors strategically each move, possibly different sets. The goal is to maximize max_{move i} wi (the amount of water in root after that move). Note that we can also decide to pour less than k liters, but maybe we always pour k to maximize potential? Not necessarily; using more water might increase max root water but might also cost more to control? Since we want to maximize the maximum root water, we want some move where a lot of water reaches root. But we might be constrained by coins: we have limited p, so we cannot close too many water-heavy tanks without paying a lot.
We need to find the maximum achievable value D = max(w_i) over moves, given we can choose initial placement (set of up to k vertices with 1 liter each), and per move closing strategies (subject to total coins spent ≤ p, but it says "p coins" initially, not a budget per move? Actually he has p coins total to spend throughout the game. So total sum over all moves of costs must not exceed p. If he runs out of coins, he cannot close doors in subsequent moves (or cannot afford). So it's a total budget of p.
We need to maximize D. This is a combinatorial optimization. Observing that water amounts are 0/1 initially, and moves only move water upward from unblocked vertices. Over time, water can accumulate at some vertices if they are closed in certain moves.
Interpretation: The tree is rooted at 1. Each vertex v has some water (0 or 1 initially). Over a series of steps (moves), water propagates upward by one level per move from vertices that are not closed. Closing a vertex prevents it from sending its water upward that move; however, it still can receive water from its children.
This is reminiscent of a process where water moves toward root, and we can delay certain water by closing vertices, which costs coins equal to the water amount at the time of closing.
Goal: maximize the peak amount at root after any move. Essentially, we want to coordinate the arrivals of water to root to create a large spike. Because water can be delayed, we can schedule different water units to reach root at the same time, increasing wi.
Observation: Since water units start at various depths, and each move they can either move up (if their current vertex is not closed) or stay (if closed). The root after a move receives all water that moved from its children that were not closed, plus possibly from deeper? Actually only direct children: water from deeper nodes can eventually reach root through multiple moves. In a given move, water that is at a node at depth d will move to depth d-1 if the node is not closed; then next moves it continues.
Thus, each unit of water (starting at some leaf or internal vertex) can be thought of as having a "time" to reach root if never blocked: equal to its depth. If we block it some moves, it takes longer.
We want to have as many water units as possible at root simultaneously at some move. But note root is emptied at the beginning of each move, so water that reaches root during a move (from its children moving water) will be present at the end of that move. Then next move, root is emptied, so those water units disappear. So each water unit contributes to exactly one wi (the move at which it reaches root). So the root water after a move equals the number of water units that reach root during that move.
Thus D is the maximum number of water units that reach root in a single move.
We have control: we can decide initial placement (choose up to k vertices at depth >=1, each gets 1 water). Then we can choose blocking strategies to delay some water units to synchronize their arrival at root.
We have a coin budget: each time we block a vertex that contains w water (w is integer), we pay w coins. Since water units are 0/1 initially, but as process goes, water amounts can accumulate at a vertex if multiple units arrive? Initially each vertex either has 0 or 1. However, when water moves from children to parent, the parent can receive multiple units, so its water amount can become >1. Indeed, water amounts can accumulate. So a vertex might contain multiple liters. That can happen, especially if we close it and let its children pour into it. Then later when we open it (or not close it), it can send all that water upward in one move. So it's possible to have water amounts larger than 1. So coins cost when closing a vertex is its current water amount. So if we let water accumulate at a vertex and then close it, it costs more.
But we want to maximize the peak at root, which is the total number of water units reaching root in a move. Since we can accumulate water at intermediate vertices and then release in a surge, we could potentially get up to k water units at root at once if we bring them all together.
But we have limited coins p. So we need to see how to minimize coin cost to achieve a given D.
We need to compute the maximum D such that there exists an initial placement (using at most k water units) and a sequence of moves (blocking decisions) with total coin cost ≤ p, leading to at least D water units reaching root in some move.
We need to find the maximum D over all strategies.
We need to find efficient solution for m up to 1e5, k and p up to 1e9.
Simplify: The process is deterministic given blocking choices. But we can think in terms of planning the "delays" per water unit.
Consider each water unit starting at some vertex v (depth d(v)). To reach root, it must travel along the unique path of length d(v). In each move, if the vertex it currently occupies is not closed, it moves up one edge; if closed, it stays. So the total number of moves it takes to reach root is d(v) + (total number of moves where it was delayed), where delays occur when the water unit is at a vertex that we choose to close during that move.
But note that when a water unit is at some vertex, that vertex might contain multiple water units; if we close the vertex, we pay the total water there. So delaying multiple water units at the same vertex costs more per move (since we pay the sum). That suggests grouping delays to minimize cost: we can delay many water units together by closing a vertex that holds them, paying the total number of units there.
Goal: Make at least D units arrive at root on the same move. This means that for the set of water units we use, we need to schedule delays such that their arrival times at root are equal. The natural arrival time without delays is depth. So we need to add extra delays to some units to equalize their total travel time. Additionally, we can also possibly make some units arrive earlier? No, they cannot arrive earlier than depth, because they move at most one level per move when not delayed. So minimum time is depth. So if we want D units to arrive at the same move T, then for each unit i starting at depth d_i, we need to add some nonnegative integer delays δ_i such that d_i + δ_i = T. So T must be at least max d_i. For each unit, we need to delay it by δ_i = T - d_i moves.
Thus the problem reduces to: We can select a set of vertices (with possible multiple units per vertex? Initially we can only put at most 1 unit per vertex, because we pour exactly 1 liter into chosen tanks. So each vertex initially can have at most 1 unit. However, later water can accumulate, but that's just multiple units merging. But initially we have at most one per vertex. So we have k units placed on distinct vertices (we can choose fewer than k, but it's suboptimal for maximizing D). For each unit, we have its depth d(v). We want to make at least D units have the same total travel time T (some integer) by adding delays. Delays are achieved by closing the vertex where the unit currently resides for some moves. The cost of delaying a unit depends on how many other units are also being delayed at the same vertex at that time. Because if multiple units are at the same vertex, closing that vertex incurs cost equal to the total number of units there for each move we close it. So to minimize total coin cost, we would like to aggregate units onto as few vertices as possible before delaying them, so that the cost per move of delaying them is just the count of units in that vertex, but if we delay them separately, cost might be sum of counts across vertices, but perhaps more moves? Actually, the total cost is sum over moves of sum of water amounts at closed vertices. So if we want to delay a set of units for a total of some number of "delay steps", we can think of each delay step as choosing a set of vertices to close; each unit contributes to the cost for each move it is delayed (since it sits in some vertex, and if that vertex is closed that move, the unit's presence adds 1 to the cost). However, if multiple units are in the same vertex, then closing that vertex for a move costs that many units at once. So total cost = sum over moves (number of units in closed vertices). Equivalent to sum over units of number of moves during which that unit was in a closed vertex.
But careful: if a unit is in a vertex that is closed, we pay for it each move that vertex is closed, regardless of whether we also close other vertices. So each unit's total delays δ_i contributes to total cost. However, if multiple units are delayed together in the same vertex for the same moves, they each incur cost. So total cost = sum_i δ_i, because each unit's delay steps are counted individually, regardless of grouping. But is there any scenario where the cost could be less than sum of δ_i? Let's verify: Suppose we have two units in separate vertices. If we want to delay each by 1 move, we need to close both vertices for one move, costing 1+1 = 2. That's sum of δ_i. If they are in same vertex, we close that vertex for 1 move, costing 2 (since two units present). So still sum of δ_i. So total cost = total number of "unit-move delays". In other words, for each unit, for each move that it does not move upward, we pay 1 coin (since its water amount is 1). If we close the vertex containing that unit, that unit incurs cost 1 that move. So total cost = sum_i δ_i.
But wait: what about when a unit is at a vertex that contains multiple units, and we close that vertex: we pay total water amount = number of units. That's exactly sum over units there of 1 per unit. So yes, total cost over whole process = sum over moves of (total number of units in closed vertices) = sum over units of (number of moves during which that unit was in a closed vertex). Since a unit moves only when its vertex is not closed, and stays when closed, the number of moves it stays (i.e., delays) equals δ_i. So total cost = ∑ δ_i. So cost is simply total delay steps across all units.
Thus the coin cost is exactly the total number of moves that each water unit is prevented from moving upward, summed over all units. Important: This holds only if we never close a vertex when it contains 0 water? That would cost 0, but we would not do that. So cost is indeed sum of delays.
But is there any additional cost from closing vertices that contain water that we are not intending to delay? Probably not; we would only close vertices to deliberately delay units. Also we might choose not to close some vertices that contain water but we might still want to move them? No cost then. So total cost is sum of delays.
Therefore the problem simplifies significantly: We have up to k water units placed at distinct vertices (non-root). We can decide an integer T (the move number at which we want D units to reach root). For each unit starting at depth d, we need to delay it by δ = T - d moves, which must be ≥ 0. The total cost across all units we choose to bring to root at time T (or earlier?) But we only care about achieving D units arriving at root at the same move. We may have extra units that arrive at other times; they don't affect the max. But we must account for total cost incurred for all units, because the coin budget is total over all moves, not only those units synchronized. So if we have more than D units, we might delay them as well, incurring cost. But we are free to place at most k units, and we could place exactly D units if that is sufficient to achieve D. However, perhaps placing more units could help? No, to achieve a max root water of D, we need at least D units arriving at root at some move. Additional units may be placed but they could be left to never reach root, or reach root at different times, but they still may incur delays and cost. Since we have limited coins, it's best to use exactly D units? Maybe using more than D can allow us to achieve D with lower cost? Possibly by using extra units to help "carry" delays? But delays are per unit; extra units only add cost. So to minimize cost for a given D, we should only place exactly D units (or at most D? We need at least D to achieve D, so we should place exactly D). But careful: Could it be beneficial to place units at shallower depths to reduce delays? Possibly. But we can choose which vertices to place the D units. So we can choose D vertices (distinct) from the tree (non-root) to place water. For each chosen vertex v with depth d(v), we need to delay it by T - d(v) moves to make it arrive at root at time T. The total cost is sum_i (T - d(v_i)). The coin budget is p. So we need to find if there exists a set of D vertices (distinct) and a T such that T >= max_i d(v_i) and sum_i (T - d(v_i)) ≤ p. Additionally, D ≤ k (since we can only place at most k units). Also we cannot place at root.
But is this sufficient? Are there any other constraints? Let's think about the process: We need to schedule delays precisely such that each unit experiences exactly δ_i delays before reaching root. But can we achieve arbitrary delays for each unit independently? Given the tree structure, we have the ability to close any vertex each move, paying cost. But there might be interactions: if two units are on the same vertex at the same time, closing that vertex delays both simultaneously. That could reduce the total number of moves needed? Actually total cost is sum of delays, regardless of concurrency. But is it always possible to achieve any set of delays δ_i for units initially placed at distinct vertices? We need to simulate to see if we can realize delays without interfering with each other and without extra cost beyond sum δ_i. Since we can close any vertex at any move, we can individually control each unit's delay. But if two units share a vertex at some time, we might be forced to delay both together if we want to delay one? Let's think.
We have a process where water units move upward along the tree. Initially, each unit is at its starting vertex. At each move, we decide which vertices to close. For a unit at vertex u (not root), if we close u, the unit stays; if we open u (don't close), the unit moves up to parent. So to achieve a delay of δ for a unit, we need to close its current vertex for exactly δ moves during its ascent. However, the unit's location changes over time. So the set of moves when we close the vertex containing it must total δ. Since we can close different vertices each move, we can independently control each unit's delays, as long as we don't have conflicts where two units are in the same vertex and we want to delay one but not the other. Because if two units share a vertex, we cannot close the vertex for only one of them; closing the vertex delays both. Similarly, if we want one to move while the other stays, we cannot because if they are together, they must both move or both stay (since moving depends on the vertex being closed or not). So we need to avoid situations where units are together at a vertex and we want different behavior. However, maybe we can separate them by previously delaying one, causing them to be at different depths. But initially they are at distinct vertices. As they ascend, they may converge at a common ancestor. If we want different delays for them, we might need to have them be at the same vertex at some time but with different desired actions: one should move, one should stay. That is impossible because the move decision applies to the vertex, not individual units. So to achieve independent delays, we must ensure that at any time, any two units that require different treatment (one needs to be delayed while the other needs to move) are not in the same vertex. That imposes constraints on the scheduling of delays.
The question: given a set of start vertices and desired total delays (δ_i), can we always schedule closings to achieve exactly those delays? Or is there a more fundamental equivalence: total cost = sum δ_i, but can we achieve any δ_i with total cost sum δ_i? Perhaps yes, if we plan delays so that units never meet while requiring conflicting actions. Is that always possible? Let's analyze.
Suppose we have two units starting at different leaves. They will travel upward along their paths to root. Their paths may merge at LCA. After merging, they will be together in the same vertex from that point onward. If we want them to have different total delays, they might need to separate again? But once merged, they cannot separate because they are indistinguishable water in the same tank; they will move together. So after merging, they must have the same remaining delays (since from that point, any delay applied to the vertex delays both). Therefore, for two units to have different total delays, they must never be in the same vertex at the same time, or if they meet, they must have already completed their required delays and be in sync such that from that point onward they have the same remaining moves? Actually, if they meet, they become co-located. From that moment, any further decisions affect both equally. So for them to have different total delays, the difference in delays must be fully applied before they meet. In other words, we need to schedule delays such that by the time they would meet, their remaining travel times (including delays) are equal, so that they can ascend together without further divergence. This is reminiscent of the classic problem of synchronizing multiple tokens on a tree with moves and delays, where total cost is sum of delays, and it's possible if and only if for any two units, the difference in delays is at least the difference in depths? Let's derive.
Let each unit i have a target arrival time T (same for all). Then required delays δ_i = T - d_i. So the delay needed for a unit is determined by its depth. Two units with depths d_a and d_b require delays δ_a, δ_b. Their difference δ_a - δ_b = d_b - d_a. So the deeper unit needs less delay? Actually if d_a > d_b (deeper), then T - d_a < T - d_b, so deeper unit needs fewer delays. That seems plausible: deeper units take longer to reach root naturally, so to arrive at same time as shallower ones, they need less extra delay. Shallower units need more delays to wait for deeper ones.
Now consider two units that have a common ancestor at depth L (distance from root). Their paths will merge at that ancestor (the LCA) when both have ascended enough to reach that vertex. Let's denote the depths: d_a, d_b. Their distances to LCA: h_a = d_a - L, h_b = d_b - L. They will reach LCA after moving up h_a steps (plus any delays they incurred before reaching LCA). They will be at LCA at times t_a = h_a + delays_before_LCA (including delays incurred while ascending to LCA). t_b = h_b + delays_before_LCA'. For them to be able to merge without conflict, at the moment they meet, they should have the same remaining path length L (to root) and we would want them to proceed together. But even if they meet, they could still have different remaining delays? If after meeting they are together, any delay applied would affect both. So to achieve total delays δ_a, δ_b, we must ensure that the sum of delays each experiences before meeting plus the delays after meeting (shared) equals δ_a and δ_b respectively. Since after meeting, delays are shared, the difference in total delays must be accounted for entirely before meeting. So we need (delays before LCA for a) + (shared delays) = δ_a, similarly for b, so the difference δ_a - δ_b must equal (delays_before_LCA for a) - (delays_before_LCA for b). Since after meeting, shared delays are equal. So it's possible if we can allocate delays before meeting such that the difference matches. But can we always allocate delays individually before meeting? Possibly, because before meeting, they are on disjoint subtrees (except at the meeting point, but they meet exactly when both arrive at LCA). Up to that point, they are in separate vertices, so we can close one vertex without affecting the other. So we can apply different delays to each unit on its path up to LCA. However, there may be constraints: the maximum number of delays we can apply to a unit before reaching a certain vertex is limited by the time? Actually, we can delay arbitrarily many moves as long as we pay. So we can make a unit wait at any vertex along its ascent. So we can set delays before LCA arbitrarily.
Therefore, given any depths and T, we can assign to each unit a schedule: at each step, decide to close its current vertex for required number of moves, as long as we pay. The only potential conflict is when two units are at the same vertex at the same time and we need to apply different delays to each. But if we ensure that by the time they meet, the remaining path lengths are the same and we have already accounted for the difference in total delays, then after meeting they can be treated identically. Is it always possible to synchronize them so that they meet at the same time? They will naturally meet when both have ascended to LCA. But if we apply different delays, they might arrive at LCA at different times. If they arrive at different times, then they are not together at the same moment; one arrives earlier. The earlier one might continue upward, possibly passing through LCA and going further up before the other arrives. Then they might never be in the same vertex simultaneously. That's okay; they don't need to be together. They could remain separate all the way to root, arriving at root at same time but via different paths? However, after LCA, their paths coincide. If one arrives at LCA earlier and moves up, it will leave LCA, and the later one will arrive later. They could still both reach root at same time if the later one catches up by having fewer delays later? But after LCA, they share the same vertices. If they are not together at the same time, they could still be scheduled independently? But once the earlier one moves up from LCA, it will go to parent. Later, when the later one reaches LCA, it may move up. But then they are on the same path but at different times. That's fine; they never occupy the same vertex simultaneously, so no conflict. So the only conflict is if they occupy the same vertex at the same move. So we need to avoid that situation where two units are in the same vertex at same time and we need to apply different actions to them (one to stay, one to move). But we can schedule delays such that they never simultaneously occupy a vertex unless they are perfectly synchronized (i.e., they have same remaining delays from that point). Let's examine if it's always possible.
Given T, we can design a schedule: Each unit i will be delayed exactly δ_i times in total. A natural schedule: For each unit, we can simply delay it at its starting vertex for δ_i moves, then let it ascend without further delays. That way, the unit starts moving after δ_i delays and then takes d_i steps to root, arriving at time δ_i + d_i = T. This schedule works: we keep the unit at its starting vertex for δ_i moves (by closing that vertex each move), then we open it and let it move upward each subsequent move (never closing any vertex on its path after that). Since we only close its starting vertex, it stays there for δ_i moves, then moves straightforwardly.
Now, could this cause conflicts? If two units have different starting vertices, they are initially at different vertices, so closing one doesn't affect the other. When they start moving, they will travel upward. They might meet at some vertex at the same time if their schedules cause them to arrive at an ancestor simultaneously. For example, unit A from deeper depth with small δ (so it starts moving early) and unit B from shallower depth with larger δ (starts later). They could potentially meet at some ancestor at the same time. Let's simulate.
Unit A: depth d_A, delays δ_A, so start moving at time δ_A (i.e., after δ_A delays, it moves one step each move). Its position at time t (t moves after initial step? Let's define time in moves. Initially, before any move, we have placed water. Then we perform move 1,2,... We need to define time. Better to define discrete time steps: At time 0 (before first move), water is placed. Each move consists of a "closing" phase (cost) then flow. We can think of each move as incrementing time by 1. The water movement occurs during the move. So after move 1, water may have moved. The root water after move i is w_i. The arrival at root is after some moves. Under our schedule: To have unit arrive at root at move T, we need it to be at root after T moves. That means after T moves, the water from that unit is in root (and then root is emptied at beginning of move T+1? But w_i is after move i. So if we want w_i to include this unit, it must arrive at root during move i. So arrival time T is the move index such that after that move, the unit is in root. So we want d_i + δ_i = T. Let's define: Initially at time 0, unit at depth d. For it to reach root at move T, it must move upward exactly d times, and be delayed T-d times. So total moves = T. So we can schedule delays anywhere along the ascent.
In the simple schedule: stay at initial vertex for δ_i moves (i.e., during moves 1..δ_i, we close that vertex, so unit does not move). Then starting at move δ_i+1, we open it and each move it moves up one level. So at the end of move δ_i + d_i, it reaches root. So arrival move = δ_i + d_i = T.
Now, consider two units A and B with depths d_A > d_B (A deeper). To have same T, δ_A = T - d_A, δ_B = T - d_B, so δ_B > δ_A. So B (shallower) delays longer at its start. B starts moving at time δ_B (move δ_B+1?), A starts moving at time δ_A. Since δ_B > δ_A, A starts moving earlier. Their paths may intersect at LCA. Suppose they are in different subtrees under root? They will eventually converge at root, but they might meet earlier at common ancestors. Could they be at the same vertex at the same time? Let's compute their positions over time.
Define time t (number of moves completed). At time t, after t moves, each unit's depth = initial depth minus number of moves it has moved (i.e., number of times it was not delayed). Since each unit i has moved in exactly those moves where its vertex was not closed. Under our simple schedule, before time δ_i, it hasn't moved; after, it moves each move. So its depth at time t (t moves completed) is:
If t ≤ δ_i: depth = d_i (hasn't moved)
If t > δ_i: depth = d_i - (t - δ_i) = d_i + δ_i - t.
Alternatively, we can think of the "progress" variable: the number of steps upward taken by time t = max(0, t - δ_i). So depth = d_i - max(0, t - δ_i).
At time t, unit i is at vertex which is ancestor at distance from root? Actually depth.
Now, suppose at some time t, both units are at the same vertex. That would mean they have same depth and also share the same ancestor path? Actually if they are at same depth, they could be different vertices. To be same vertex, they must be at same depth and also be at same ancestor (i.e., they have converged). Since they are in the same tree, if they are at same depth and are on the same path from root to leaves, they could be the same vertex if they have reached a common ancestor. But generally, they will be at the same vertex only if they have ascended enough to reach their LCA and then possibly beyond.
Given our simple schedule, they might meet at the LCA at same time? Let's find condition.
Let L be depth of LCA (distance from root). For unit i, it reaches depth L at time t_i such that d_i - max(0, t_i - δ_i) = L => max(0, t_i - δ_i) = d_i - L => if t_i > δ_i, then t_i - δ_i = d_i - L => t_i = δ_i + d_i - L. If t_i ≤ δ_i, then d_i = L, but L ≤ d_i; if d_i = L then t_i can be ≤ δ_i? Actually if d_i = L, the unit is already at LCA initially; then it might be delayed there. So we need to consider.
For typical case where d_i > L, the time to reach depth L is t_i = δ_i + (d_i - L) = T - L (since δ_i + d_i = T). Indeed t_i = T - L. So both units reach depth L at the same time t = T - L, regardless of their depths! Because T is same, L is same. This is interesting: Under our simple schedule, both units will arrive at their LCA exactly at the same time (if they ever get there). Let's check: For unit i, arrival at depth L (the depth of LCA) occurs when it has moved d_i - L steps upward. Since it moves after δ_i delays, the move count when it reaches depth L is δ_i + (d_i - L) = T - L. Since T and L are constants for the pair, both arrive at same time. Moreover, at that time they are at depth L, but are they at the same vertex? They both are at the LCA? Actually, if L is the depth of LCA, then the ancestor at depth L on the path from each unit to root is exactly the LCA (the deepest common ancestor). So yes, both units will be at the LCA at time T - L. At that moment, they are together. Then after that, they will both ascend together because they have the same remaining depth L to root, and they are both at same vertex with same schedule (since after meeting, we haven't specified schedule but in our simple schedule, after the initial delays, they both move every step. At time t = T - L, both have just arrived at LCA. In the next move (move number t+1), they will both be at the LCA and we must decide whether to close that vertex. In our simple schedule, we never close vertices after the initial delays. So at that move, the vertex (LCA) will be open, so both units will move up to its parent. So they will continue together, and they will reach root together at time T. So under this schedule, they will meet at LCA at same time and then travel together. That's fine. There is no conflict because at the time they are together, we don't need to apply different delays (they both should move, and they do). So the schedule works without conflict.
What about more complex schedules? The simple schedule works: delay each unit at its starting vertex for δ_i moves, then let it go. No need to close any other vertices. So we can achieve any set of δ_i as long as we can pay the cost sum δ_i, with no additional constraints. The only potential issue: can we close the starting vertex of each unit for δ_i moves independently? Since they are distinct vertices initially, yes. However, if two units start at the same vertex? But we can only put at most 1 unit per vertex initially, because we pour exactly 1 liter per chosen tank, and each tank can be chosen at most once? The problem says: "Mashmokh chooses some (no more than k) of these tanks (except the root) and pours into each of them exactly 1 liter of water." It doesn't explicitly forbid choosing same tank multiple times, but "pours into each of them exactly 1 liter" suggests each chosen tank gets exactly 1 liter; you can choose a tank only once. Since there is exactly one tank per vertex, you can put at most 1 liter per vertex initially. So initial placement is a subset of vertices with at most one unit each. So no two units share the same start vertex.
Thus the simple schedule is feasible. So the necessary and sufficient condition to achieve D units arriving at root at same time T is: we can choose D vertices (distinct) with depths d_i, and a T >= max(d_i), such that total delay cost = ∑ (T - d_i) ≤ p, and also D ≤ k. Additionally, we must ensure that T is integer and moves are positive? T can be any positive integer? We can have T = 0? No, because moves start from 1; water reaches root after at least one move if depth 1? Actually if depth = 1, unit can reach root in move 1 if not delayed (d=1, T=1, δ=0). So T must be at least 1? Possibly T can be 0? At time 0 (before any move), root is empty? Not considered. So we consider T >= 1. But it's okay.
Thus the problem reduces to: Given a rooted tree with depths, we need to select up to D vertices (with D ≤ k) such that there exists T >= max depth among selected vertices, minimizing total delay cost = sum_i (T - d_i). Actually for a given D, we want to maximize the chance to satisfy cost ≤ p. So we want to see if there exists some T and a set of D vertices such that sum_i (T - d_i) ≤ p. That is equivalent to: For some T, we can pick D vertices all with depth ≤ T, and sum_i (T - d_i) = DT - sum d_i ≤ p. Since we can choose which vertices, we would like to minimize sum d_i for given D (to reduce cost) because T will be at least max depth. More precisely, for a fixed set S, the minimal T to achieve same arrival time is max_{v∈S} d(v). If we choose T larger than that, cost increases because we add extra delays: each extra delay adds D to cost. So it's never beneficial to choose T > max depth, because that would increase cost without benefit. Indeed, to minimize total cost for a given set S, we should set T = max depth in S. Because any larger T would add D(T - maxdepth) to cost, which is non-negative. So we set T = max d_i. Then total cost = ∑ (maxd - d_i) = D*maxd - ∑ d_i.
Thus the condition becomes: There exists a set S of D vertices (distinct, non-root) such that if we let M = max_{v∈S} d(v), then D*M - sum_{v∈S} d(v) ≤ p, and |S| = D ≤ k.
We want to maximize D (integer) satisfying this.
Now we need to compute the maximum possible D for given tree (depths of vertices, except root) and constraints k and p. Depth is measured from root (depth 0 at root). For vertices, depth ≥ 1.
This is reminiscent of choosing D vertices to minimize DM - sum(d). Equivalent to: For a candidate D, we need to see if we can pick D vertices such that Dmaxdepth - sumdepth ≤ p. Since D and maxdepth are linked, we can think of grouping vertices by depth.
Let’s denote for each possible depth value h (≥1), we have a set of vertices at depth h. Let cnt[h] = number of vertices at depth h.
If we choose a set S with maximum depth M, then S can include vertices from depths ≤ M. The sumdepth is sum of depths of chosen vertices. To minimize DM - sumdepth for fixed D and M, we want sumdepth as large as possible, because DM is fixed given D and M. So for given M, we should pick the deepest vertices (i.e., those with highest depths) but not exceeding M, because that would increase sumdepth, reducing the cost. Actually D*M - sumdepth decreases as sumdepth increases. So to achieve low cost, we want to pick vertices with as large depths as possible. However, we cannot exceed M because max depth is M. So the best is to pick vertices from depth exactly M, then if need more, from M-1, etc. So for a given M, we want to select as many vertices as possible from depths >=? Actually to maximize sumdepth for a given D and M, we should pick vertices with highest depths ≤ M, i.e., from deepest levels first.
But we also have constraint D ≤ k. So for each possible M, we can consider selecting up to min(k, total vertices with depth ≤ M) vertices, but we need to compute minimal possible cost for a given D and M, or for given D, we can choose M to minimize cost.
Alternatively, we can think: For a given D, we want to minimize cost = D * M - sum_depth over a set of D vertices. Since M = max depth among chosen, it's natural to consider M as the depth of the deepest chosen vertex. Let’s denote that depth as h. Then cost = Dh - sum_{v in S} d(v). To minimize cost for given D, we want h as small as possible and sum_depth as large as possible. But h is the maximum depth, so it's at least the depth of the D-th deepest vertex if we sort by depth. Actually if we want to minimize cost, we would like to pick D vertices with as small maximum depth as possible, but also with depths as large as possible within that bound. There's a tradeoff: picking a shallower maximum depth h reduces Dh, but also reduces the maximum possible sumdepth because we are limited to depths ≤ h. The optimal is likely to pick the D deepest vertices overall? Let's test: Suppose we sort all vertices by depth descending. Let depths sorted descending: d1 ≥ d2 ≥ ... ≥ d_N (N = m-1, excluding root). If we pick the top D deepest vertices, then M = d1 (the largest among them). Then cost = Dd1 - (d1 + d2 + ... + d_D) = (D-1)d1 - (d2+...+d_D). This could be large if d1 is much larger than others. Alternatively, we could drop the deepest vertex and pick a slightly shallower set to reduce M, potentially lowering cost. Example: depths: [100, 1, 1, ...]. For D=2, picking two deepest gives M=100, cost = 2100 - (100+1)=100-1=99? Actually compute: D=2, M=100, sum=101, cost=200-101=99. Alternatively, pick two vertices of depth 1: M=1, cost=2-2=0. That's much smaller. So obviously picking deepest is not optimal for cost; we want to avoid very deep vertices because they force a large M and also increase sum less than DM. Actually sum of depths of deepest D may be small relative to Dmaxdepth. So we need to find a set of D vertices that minimizes DM - sum.
This looks like we can choose any D vertices, so we should choose D vertices that are as shallow as possible? But wait, if we choose shallow vertices, M is small, but sumdepth also small. Let's compute cost for shallow vertices: Suppose we pick D vertices all at depth h. Then M = h, sum = D*h, cost = 0. So that's ideal (cost zero). But we may not have enough vertices at a given depth. So we need to pick vertices from various depths, but we can achieve zero cost if we pick all vertices from the same depth. But note: we cannot pick root, but we can pick any non-root vertices. So if there are at least D vertices at some depth h, we can set M = h and cost = 0, satisfying p≥0. So if for some depth h, cnt[h] ≥ D and D ≤ k, we can achieve D with zero cost. Therefore, the maximum D could be limited by the maximum count at any depth, but also by k and p.
If we have p > 0, we can afford some cost to include deeper vertices or mix depths. So overall we need to find largest D such that there exists a multiset (set) of D vertices with max depth M and total cost ≤ p.
This is similar to: For each possible M, what is the maximum number of vertices we can select with max depth ≤ M such that cost = DM - sum(d) ≤ p? But we are not forced to pick all vertices from depths ≤ M; we can also pick some deeper than M? No, M is the maximum depth, so all chosen depths ≤ M. So for a given M, we can pick any subset of vertices with depth ≤ M. If we pick D vertices with depths d_i ≤ M, the cost is DM - sum d_i. Since M is fixed, to minimize cost for given D, we want to maximize sum d_i, i.e., pick the deepest vertices within ≤ M. So for a fixed M, the minimal possible cost for selecting D vertices is: DM - (sum of largest D depths among vertices with depth ≤ M). Let’s denote for each M, sort depths ≤ M descending, and compute prefix sums. Then for each D up to total number of vertices with depth ≤ M, the minimal cost is DM - prefix_sum[D]. We need this ≤ p, and D ≤ k.
Thus we can iterate over possible M (depth values) and find maximum D such that there exists D ≤ min(k, total_vertices_up_to_M) and D*M - prefix_sum[D] ≤ p. Then answer is max over M of such D.
M can be up to max depth in tree, which could be up to m-1 (maybe 1e5). But we can do this efficiently.
But note: The vertices are in a tree, but we only care about depths. So we just need depth distribution (count per depth). That's easy to compute via BFS. Since the tree is rooted at 1, we can compute depth for each node.
Now we need to compute for each depth threshold M, the sorted list of depths ≤ M? Actually to get largest D depths among those ≤ M, since depths are integer, the largest D depths are simply the deepest ones, i.e., take vertices from as deep as possible up to M. So for a given M, we can consider taking all vertices with depth exactly M, then M-1, etc., until we have D vertices. So the sum of depths for the deepest D vertices within [1..M] is sum of depths of the D deepest vertices among that set. Since depths are integers, we can precompute for each depth the count, and then we can compute prefix sums over depths descending.
Approach: Let maxDepth = max depth among vertices (excluding root). For each depth h from 1 to maxDepth, let cnt[h] = number of vertices at that depth.
We want to consider M from 1 to maxDepth. For each M, we consider selecting some number of vertices from depths 1..M, with the selection being the deepest ones first. This is equivalent to: for a given D, the minimal cost achievable is D * (minimum possible M) but we are iterating M.
Alternatively, we can think of the problem as: we need to choose D and a set S; cost = D * maxDepth(S) - sumDepth(S). To minimize cost for given D, we can treat it as a kind of knapsack but there is structure.
Idea: Since depths are small (up to 1e5) and total vertices up to 1e5, we can compute for each possible D the minimal cost needed. Then we can binary search D.
But computing minimal cost for each D directly might be doable with a sliding approach: The cost function can be expressed as: For a chosen set S, let depths sorted increasing: d1 ≤ d2 ≤ ... ≤ d_D. Then M = d_D. Cost = Dd_D - sum_i d_i = sum_i (d_D - d_i). So it's the sum of differences between the maximum depth and each depth. This is like we have a multiset of depths, and we pay for each selected vertex the extra delay needed to bring it up to the maximum depth among them. So if we think of "synchronizing" arrivals by delaying shallower ones, the cost is total extra waiting time for the shallower ones relative to the deepest one (which needs no extra delay). That's intuitive: we pick a deepest vertex (with depth M), and for every other vertex with depth d, we need to delay it by M-d moves. So cost = sum_{v∈S} (M - d(v)). That is exactly DM - sum d. So we need to choose S and M such that M is max depth in S.
Thus, for a given D, we want to minimize sum_{v∈S} (M - d(v)). This is like we want to select D vertices, and we pay a penalty equal to the gap between the maximum depth in the set and each vertex's depth. This penalty is zero if all depths are equal. So we want to pick D vertices that are as "depth-concentrated" as possible.
We can think: Choose a depth threshold M. Then we can include any vertices with depth ≤ M. The penalty for a vertex at depth d is M - d. So if we pick a set S all with depths ≤ M, cost = Σ (M - d). To maximize |S| under cost ≤ p, we would pick vertices with smallest penalty (i.e., deepest d) first, because they give lower M-d. So for each M, we can sort vertices by depth descending and take as many as possible until the cumulative cost exceeds p, subject to total number ≤ k.
So algorithm: For each possible M (from 1 to maxDepth), consider vertices with depth ≤ M. Sort them by depth descending (or equivalently by penalty ascending). Since depths are integers, the penalties are (M - d). The sum of penalties for the t deepest vertices is t*M - sum_{i=1..t} d_i, where d_i are the t deepest among those ≤ M. We want the maximum t such that t ≤ k and cost ≤ p.
Now, maxDepth can be up to 1e5, and we need to do this efficiently. We can precompute for each depth the count and also cumulative sums over depths in descending order? Since depths are discrete, we can process M in increasing order and maintain a data structure of vertices with depth ≤ M, sorted by depth. But we need to quickly compute prefix sums of the deepest t vertices. As M increases, the set of eligible vertices expands (adding vertices at depth M). We also need to consider that the penalty for existing vertices changes because M increases: previously for M-1, penalty for a vertex at depth d was (M-1 - d); now for M, it's (M - d) = (M-1 - d) + 1. So all existing vertices' penalties increase by 1. That makes it tricky to maintain incrementally.
But we could think differently: Instead of iterating M, we can think of selecting the set S directly and compute M = max depth in S. Since M is one of the depths of vertices we select, and we can always assume that the deepest vertex in S is the one with maximum depth; maybe we can iterate over candidate M as the depth of the deepest selected vertex. For each possible M, we can consider selecting some number of vertices with depth ≤ M, but we are free to also not include all vertices at depth M? Actually, if M is the maximum depth, then we must include at least one vertex at depth M, otherwise M would not be max. But we can include any number of vertices from depths ≤ M. For cost calculation, including a vertex of depth M contributes 0 penalty, so we would definitely include as many depth M vertices as possible, because they are "free" (no cost). Then we may include vertices of shallower depths, but they incur positive penalty.
Thus, for each M, let’s define:
- Let cnt_M = number of vertices at depth M (non-root). These have penalty 0.
- For depths d < M, penalty = M - d.
We can select up to cnt_M vertices from depth M at zero cost. Then we can select additional vertices from shallower depths, but we must consider ordering by penalty. The best is to take vertices with highest depth first, i.e., from depth M-1, then M-2, etc., because they have smaller penalty.
So for each M, we can compute the maximum number of vertices we can select (total) with total penalty ≤ p, subject to total ≤ k. This is like we have groups of vertices at each depth d, each with weight (penalty) = M - d. We want to take as many items as possible, with total weight ≤ p, and we can take at most cnt[d] items from each depth d, with items sorted by increasing weight (which corresponds to decreasing depth). This is a bounded knapsack but with weights increasing as depth decreases, and we can solve by taking from the smallest weight first (i.e., deepest first). So we simply take all vertices from depth M (weight 0), then from depth M-1 (weight 1), then M-2 (weight 2), etc., until we either run out of vertices or exceed p or reach k.
Thus for each M, we can compute the maximum t as:
t = 0, remaining cost = p.
For d from M down to 1:
available = cnt[d]
weight = M - d
Take x = min(available, floor(remaining_cost / weight))? Actually careful: weight might be 0 for d=M. For d=M, weight=0, we can take all available without cost, up to k - t. So we take all from depth M (up to k).
For d<M, weight≥1. We can take as many as possible from that depth without exceeding remaining cost. But note that we want to maximize total count, so we should take as many as possible from each depth starting from highest d (smallest weight) until we fill k or run out of cost.
But we must also consider that we might not take all from a depth if we have remaining cost, but we should take as many as we can, because each item adds 1 to count and consumes weight (penalty). Since the goal is to maximize count, we should take all items from the smallest weight groups first. That is exactly the greedy algorithm for fractional knapsack with integer items where weights are increasing. Since all items from same depth have identical weight, we should take them all before moving to next depth, as long as weight ≤ remaining cost per item. But if remaining cost is limited, we might only take some of a depth. That's optimal because all items have same value (1) and weight, and weights are increasing as we go to shallower depths. So greedy by taking all from depth M (weight 0), then all from depth M-1 (weight 1), then all from depth M-2 (weight 2), etc., until we either hit k or run out of cost.
Thus for each M, we can compute t(M) = maximum number of vertices we can select with max depth ≤ M and total penalty ≤ p, also ≤ k.
But careful: The penalty formula depends on M. So for a fixed M, the penalty for a vertex at depth d is M-d. So if we include vertices from depths less than M, they incur cost. So indeed we can compute t(M) as described.
Then the answer is max over M of t(M).
Now we need to compute this efficiently for M up to maxDepth (which could be up to 1e5). For each M, we would need to sum over depths from M down to 1, which could be O(maxDepth^2) worst-case. Need faster.
We can precompute prefix sums over depths to answer queries like: total number of vertices with depth between L and R, and total sum of depths in that range. Then for a given M, if we decide to take all vertices from depths >= D0 down to some threshold, we can compute how many we can take given cost limit.
Observation: The greedy selection for a given M is: take all vertices with depth = M (cost 0), then all with depth = M-1 (cost 1 each), then all with depth = M-2 (cost 2 each), etc. This is like taking vertices in descending depth order. So the total cost for taking all vertices with depth ≥ some threshold L is: Σ_{d=L}^{M} cnt[d] * (M-d). If we take all vertices from depth L to M, the cost is some function. Then we might stop in the middle of a depth level, taking a partial count from the next depth (shallower) where the weight is w = M - d.
Thus for each M, we can binary search on the number of vertices taken from the deepest ones, but we need to incorporate the cost structure which is like a weighted sum.
Alternative viewpoint: Since depths are integers, we can think of the multiset of depths. For each M, we consider the sorted list of depths (only those ≤ M) in descending order. Let this sorted list be a sequence a1 ≥ a2 ≥ ... ≥ a_N' (N' = total vertices with depth ≤ M). Then the cost for taking the first t vertices (i.e., the t deepest) is: Σ_{i=1}^{t} (M - a_i) = tM - Σ_{i=1}^{t} a_i. This is increasing in t. We need the largest t ≤ min(k, N') such that tM - prefix_sum[t] ≤ p.
So for each M, we can find the largest t satisfying this using binary search if we can quickly compute prefix sums of depths for the sorted descending list. But building this list for each M would be heavy.
We can precompute for all depths the counts and cumulative counts from the top. Let’s define for each depth d, cnt[d]. Let total vertices with depth ≥ d be suffix sum. But the sorted descending list is essentially: all vertices of depth M, then depth M-1, ..., depth 1. So the prefix sum of the sorted list for first t vertices can be computed if we know how many from each depth we have taken. The t deepest vertices will take all vertices from depth M, then M-1, etc., until we have taken t.
Thus for a given M and t, we need to find the depth threshold d0 such that total number of vertices with depth > d0 (i.e., depths in (d0, M]) is less than t, and including some from depth d0. More precisely, we can define for each M, the cumulative counts from the top: let suffix sums starting at M: S_cum_cnt[M] = cnt[M]; S_cum_cnt[d] = cnt[d] + S_cum_cnt[d+1] for d from M-1 down to 1. But we can precompute global suffix sums? However, M varies, so the suffix sum is relative to M. But we can precompute arrays for all depths, and then for each M we can query the total number of vertices with depth between some range quickly using prefix sums over depth.
Suppose we have an array cnt[1..maxDepth] (depth from 1). We can compute prefix counts and prefix sums of depths (weighted by depth). For a given M, the sorted descending list is: start from depth M, then M-1,...,1. So the prefix of t deepest corresponds to taking all vertices from depth M down to some depth L+1, and then some from depth L, where L is the depth such that cumulative count from depth L+1 to M is < t and cumulative from L to M is ≥ t.
Let total_count_above_L = sum_{d=L+1}^{M} cnt[d] (i.e., depths > L). Then need to take extra from depth L: need x = t - total_count_above_L, where 0 ≤ x ≤ cnt[L]. Then prefix sum of depths = sum_{d=L+1}^{M} cnt[d]*d + x * L.
Thus cost = t*M - (sum_{d=L+1}^{M} cnt[d]*d + x * L). We need to check if ≤ p.
Therefore, if we can for each M quickly find the maximum t that satisfies the inequality, we could binary search t. But we also have the constraint t ≤ k. So we can compute t_max(M) = min(k, total_vertices_up_to_M) as upper bound.
Now, we need to compute the maximum t such that cost(t) ≤ p. Since cost(t) is monotonic increasing in t (because adding a vertex with non-negative penalty increases cost), we can binary search t for each M. However, M can be up to 1e5, doing binary search per M might be O(maxDepth * log N) which is ~ 1e5 * log 1e5 ~ 1e6, acceptable. But we need to evaluate cost(t) quickly. For a given M and t, we need to find the depth L where the t-th deepest vertex lies (i.e., the depth of the t-th deepest among depths ≤ M). This is like order statistics in a multiset defined by cnt array. Since depths are bounded (maxDepth ≤ m), we can precompute prefix sums of cnt and sumDepth (cnt[d]*d) over depth. Then for a given M, we can find L such that total count of depths > L is < t ≤ total count of depths ≥ L. But careful: we need to consider depths only up to M. So we need to query cumulative counts within [L, M] etc.
We can precompute arrays:
- totalCnt[d] = number of vertices with depth exactly d.
- prefixCnt[d] = sum_{i=1}^{d} totalCnt[i] (for depths up to d).
- prefixSum[d] = sum_{i=1}^{d} totalCnt[i] * i.
But we need suffix sums relative to M. For a given M, we can compute cumulative counts from the top down to 1 using prefix sums: sum_{i=L}^{M} cnt[i] = prefixCnt[M] - prefixCnt[L-1].
Similarly, sum_{i=L}^{M} cnt[i]*i = prefixSum[M] - prefixSum[L-1].
To find the depth L such that total count from L+1 to M < t ≤ total count from L to M, we can binary search over L. Since depth values are up to 1e5, for each t we could binary search L, leading to O(log^2) per cost evaluation. That might be heavy if we do it for each M and each t in binary search.
But we can perhaps compute the maximum t for each M in O(log maxDepth) using a different method.
Observation: The cost function for taking the t deepest vertices (with depths ≤ M) is t*M - sumDepths(t), where sumDepths(t) is sum of the t largest depths ≤ M. Since depths are integer and we have counts, we can compute sumDepths(t) via a function that finds the t-th largest depth and sums all depths above that.
We can precompute a data structure like a Fenwick tree over depths to support queries: given M, find sum of largest t depths ≤ M. But M varies across queries. However, we could process M in increasing order and maintain something? Or perhaps we can directly iterate over possible maximum depth M and compute t_max using a two-pointer approach.
Alternate viewpoint: Since the answer D is at most k and at most total vertices, and maxDepth is up to 1e5, we could for each M compute t_max by iterating over depths descending from M and accumulating until cost exceeds p. Since the total work over all M could be O(maxDepth^2) if naive, but we can optimize by noting that as M increases, the set of vertices expands and the costs increase, but we might be able to use a sliding window or something.
But perhaps we can think differently: The answer D is the maximum number such that there exists M with D ≤ min(k, prefixCnt[M]) and D*M - sum_of_D_largest_depths_up_to_M ≤ p. Instead of iterating over M, we could binary search D and check if there exists M satisfying the condition. For a fixed D, we need to see if there exists M such that we can pick D vertices with max depth ≤ M and cost ≤ p. That's like: we need to find minimal possible cost for selecting D vertices. If minimal cost ≤ p, then D is feasible.
So define f(D) = minimal possible total penalty (i.e., minimal over all choices of set S of size D of (maxDepth(S)*D - sumDepth(S))). Compute f(D) and check f(D) ≤ p and D ≤ k. Then binary search D.
Now, can we compute f(D) efficiently? This is like: we need to pick D vertices to minimize D * M - sumDepth, where M = max depth in S. Equivalent to: for each possible M, the minimal cost for size D with max depth ≤ M is DM - sum_of_D_largest_depths ≤ M. So overall f(D) = min_{M} ( DM - sum_of_D_largest_depths_≤ M ). Since D*M increases with M, and sum_of_D_largest_depths_≤ M also increases with M (as more deeper vertices become available), f(D) is the minimum over M of that expression.
We can compute for each D the best M. Since D up to maybe 1e5 (k up to 1e9 but m ≤ 1e5, so D ≤ m-1), we can compute f(D) for all D up to m-1 maybe in O(m log m) by scanning M.
But note k could be larger than m-1, but we cannot pick more vertices than there are (non-root vertices count = m-1). So D ≤ min(k, m-1). So D ≤ 1e5.
Thus we could compute f(D) for each D from 1 to m-1 and then find the maximum D with f(D) ≤ p. That would be O(m * something). Need to compute f(D) efficiently.
Let’s denote for each depth d, cnt[d]. We can precompute arrays that allow us to get the sum of the D largest depths among all vertices (i.e., unrestricted) easily: that would be sum of deepest D depths overall. But that's for M = max depth overall. However, f(D) might involve a smaller M if picking deep vertices leads to large M and high D*M - sum. We need to find the optimal M that balances.
Consider D fixed. We need to choose M (the max depth in set) and pick D vertices with depth ≤ M to minimize DM - sum. Since sum is maximized by picking the deepest D within ≤ M, the minimal cost for given M is C(M) = DM - S(M), where S(M) = sum of the D largest depths ≤ M (or if total vertices with depth ≤ M < D, then C(M) is infinite). So we need min over M where cnt_total_up_to_M >= D of C(M).
C(M) = DM - S(M). As M increases, DM increases by D per increment. S(M) also increases, but possibly in jumps when M passes a depth that adds new deeper vertices. At depths where cnt[d] > 0, when M increases from d-1 to d, S(M) may increase because we can now include vertices of depth d, which are deeper than any previous. In fact, when M reaches a new depth value d, the set of available depths expands to include depth d. The D largest depths among ≤ M will now include some of these new depth d vertices if they are among the top D.
Thus C(M) is piecewise linear. We could try to compute it by scanning M and maintaining the sum of the D largest depths seen so far. However, D varies, making it heavy.
Alternative: We can compute the maximum D for which there exists M satisfying C(M) ≤ p. That's what we need.
We might try to iterate over M as the candidate maximum depth, and compute the maximum t we can achieve for that M (as earlier) and take max. Since M max depth is ≤ m, we can iterate M from 1 to maxDepth and compute t_max(M). This might be feasible if we can compute t_max(M) in O(1) or O(log m) each.
We can attempt to compute t_max(M) by using the fact that as we include more vertices (by increasing t), the cost function is monotonic. We need the largest t such that t*M - sum_{i=1}^{t} d_i ≤ p, where d_i are depths sorted descending ≤ M.
Let’s define for each M, we can precompute the sorted list of depths? Not directly.
But we can process M in increasing order and maintain a data structure that holds the depths of all vertices with depth ≤ M, sorted descending. Then we can query the maximal t satisfying cost condition. As M increases, we add all vertices at depth M to the structure. Then we need to quickly find t_max such that t*M - (sum of t largest depths in the structure) ≤ p. This is reminiscent of maintaining a multiset and being able to compute prefix sums of the largest t elements. Since we add elements as M increases, we could use a Fenwick tree over depth values (since depth values are up to maxDepth). We can maintain counts and sum of depths for all added vertices. Then to compute sum of t largest depths, we can binary search on depth threshold to find the depth such that there are at least t vertices with depth >= some value, and then compute sum.
Specifically, we have a Fenwick tree (BIT) that supports:
- add depth d with count +1, sumDepth + d.
- query total count of depths >= some value (i.e., suffix). Since depth values are up to 1e5, we can store counts per depth, and use prefix sums. For a given t, we want to find the sum of the t largest depths. This can be done by performing a binary search on depth to find the smallest depth L such that count of depths >= L is ≤ t? Actually we want the sum of the t largest. Let total count = N. We want sum of top t. We can find the depth value d0 such that count of depths > d0 is < t and count of depths >= d0 is >= t. Then we can compute sum = sum_{depth > d0} cnt[d]*depth + (t - count_above) * d0.
Using BIT, we can compute cumulative counts and sums from high depths downwards. Since depths are positive and up to maxDepth, we can store BIT from 1 to maxDepth and query suffix sums by using total minus prefix up to d-1. So we can binary search for d0 in O(log maxDepth). Then cost(t) = t*M - sum_top_t. We need to find max t ≤ min(k, N) such that cost(t) ≤ p.
Now, if we iterate M from 1 to maxDepth, each time we add all vertices at depth M to the BIT (so N increases). Then for each M, we need to compute t_max. We could binary search t over [0, min(k, N)]; each cost evaluation takes O(log maxDepth) (binary search for d0 + BIT queries). So per M, O(log N * log maxDepth). With M up to 1e5, this