Merge whenever possible
Assign weight to a level- item. A merge preserves total weight of each type and frees one slot. Repeated merging leaves at most one item at each level below . This normalized representation is uniquely determined by binary carries and uses the fewest slots among representations with the same weight.
Fix an entire sequence of generated types. Whenever another strategy can continue generating along this sequence, the fully normalized strategy can also continue, since it has at least as much free space. As soon as total star weight reaches , merging can create a level- star. Thus immediate merging is no worse for every possible sequence of outcomes. We may normalize after every generation and generate again whenever a slot remains.
DP states
Let and . Before success, normalized stars are represented by a mask . Moons below level are represented by a mask . Each level- moon permanently occupies a slot.
Let be the number of slots left after excluding those permanent moons, and let be the success probability. The number of occupied remaining slots is . If it is at least , no new item can be generated and the value is zero. Initialize the layer to zero.
A generated star increments , automatically performing all binary carries. Reaching is immediate success. A generated moon increments ; reaching creates a permanent moon, resetting to zero and decreasing .
With and ,
The answer is . A transition that creates the target succeeds even if it uses the last free slot. A maximum-level moon cannot be discarded and must reduce .
Process in increasing order and in decreasing order. Only the current and previous capacity layers are needed. Time is and space is , with at most state evaluations under the full limits.
Subtasks
For subtask 1, memoize a vector containing the actual number of items of every type and level. Perform an available merge, or branch into the two generated types when no merge remains and space is available. There are at most count vectors, at most in this subtask. This is the supplied naive implementation.
For subtask 2, , so the first generated star wins. If every generated item is a moon, the inventory first gets stuck after
generations. The answer is , computed in time including the inverse.
Modular arithmetic
Let . Compute and . Every generation increases total weight by one, and inventory weight is at most , so only finitely many generations are possible. The reduced denominator divides a power of and is invertible because .
Each sum of two probability products is below , so signed 64-bit arithmetic suffices. The exact reduced fraction need not be constructed.
The independent forward reference propagates probability mass by total star and moon weight. For small cases, verification also compared every merge and generation action using exact rational optimal-policy search.
Solution written by GPT