The model solution only manages $C = 44$? The worst case can be pushed down to $C\le28$, with a deterministic scheme that neither relies on random hashing nor requires same-valued siblings to be visited in a fixed order.
There are two core improvements: encoding the identity of a long chain jointly in its first two nodes, which makes the number of long chains recovered per round the product of two value-range sizes; and turning the identification of the remaining singleton leaves into subset counting, so that we no longer need to assign a distinct value to every leaf in each round.
Below are the full construction, a correctness proof, a finite parameter verification of the worst-case bound, and the implementation. The problem's constraints are $N\le1000$ and $M\le200$, and the objective to minimize is $C=K+B$, where $B$ is the largest value used across all insert calls, so there are really $B+1$ usable colors.
1. First, decompose the tree into chains
Process the leaves $0,1,\ldots,M-1$ in order. For leaf $i$, repeatedly call insert(i,...) until it returns false, and let $\ell_i$ be the number of successes.
The balls newly placed this way necessarily form a top-down chain whose last node is leaf $i$. The chains are pairwise disjoint and cover the whole tree, so $N=\sum_i\ell_i$. Except for chain $0$, which contains the root, the head of every chain hangs off some earlier chain.
Call a chain with $\ell_i\ge2$ a long chain, and one with $\ell_i=1$ a singleton leaf. One important property:
Every internal node belongs to a long chain. Once all long chains are recovered, the complete internal skeleton is already known, and all that remains is the parents of a number of leaves.
During the first filling pass, we recover an initial subtree along the way.
When $M\le8$, give chain $i$ the color $M-1-i$ throughout; a single collect then recovers the entire tree, giving $C=M\le8$.
From here on assume $M>8$. Give the first $8$ chains the colors $8,7,\ldots,1$ respectively, and give every remaining chain the color $0$. After filling, call collect once and delete all the $0$s from the returned sequence; what remains is the preorder traversal of the subtree formed by the first $8$ chains.
Why can this be decoded directly? Because chains added later have smaller colors, any other chain hanging off a given chain is always traversed before that chain's next node. Maintain a stack: start a chain when a color first appears, and close it once that color has appeared $\ell_i$ times.
Let $D$ be the total number of long chains, and $a$ the number of long chains among the first $8$. At this point we know $a$ long chains and $8-a$ singleton leaves, and the number of singleton leaves still to be located is $s=M-D-8+a$.
From now on we always add the remaining long chains in the original leaf order, temporarily skipping the singleton leaves. Skipping them does not change where any long chain's balls land, since they contain no internal nodes.
2. Encoding a long chain with two nodes
This part first solves a basic problem: how can we recognize already-known internal nodes in the returned sequence using only a very small range of values?
Suppose $d$ long chains have already been recovered. Keep all known internal nodes, but prune the known leaves as follows when filling this round: if an internal node has an internal child, do not fill any of its leaf children; otherwise keep exactly one leaf child.
The auxiliary tree obtained this way has a convenient property: every internal node either has only internal children, or has exactly one leaf child. The auxiliary tree has at most $d$ leaves, because every bottommost internal node must be the last internal node of some recovered long chain.
Take $b$ with $b^2\ge d$. Using the colors $0,\ldots,b-1$, we want the pair $(c(v),\min_{w\text{ a child of }v}c(w))$ to be pairwise distinct across any set of sibling internal nodes $v$.
This property means: seeing an internal node's color and then the color of its first old child tells us exactly which node it is. It doesn't matter if same-valued siblings are reordered arbitrarily; the problem does allow such reordering, and we must not assume their order is stable.
The colors are constructed as follows.
Process bottom-up. For an internal node with a single leaf child, set that leaf's color to $0$.
For every other internal node $u$, first recurse on all children. Let $d_v$ be the number of distinct colors currently used among the children of child $v$. Lay intervals of lengths $d_v$ consecutively along the integer line starting at $0$; let $[L_v,R_v]$ be the interval assigned to $v$.
Set $c(v)=\lfloor R_v/b\rfloor$, and rename the existing color equivalence classes of $v$'s children, in order, to $L_v\bmod b,(L_v+1)\bmod b,\ldots,R_v\bmod b$.
This operation is legal and meets the requirement:
If $v$'s subtree has $L$ auxiliary-tree leaves, induction gives $d_v\le\lceil L/b\rceil\le b$. At the same time, the sum of $d_v$ over all children of a node is at most the number of leaves in its subtree, hence at most $b^2$, so all colors produced lie in $0,\ldots,b-1$.
For siblings with the same color, the right endpoints of their intervals lie within a common block of length $b$. Since each segment has length at most $b$, at most the first segment crosses the modular boundary; the starting points of the remaining segments are strictly increasing after taking the modulus. Therefore the minimum child color is pairwise distinct across them.
Moreover, renaming color equivalence classes bijectively does not destroy the pair-uniqueness already established within the subtree.
Since the auxiliary tree's structure is known, filling is easy as well: pre-select one retained descendant leaf for each node, and insert balls toward that leaf in preorder. Because the ancestors are already full, the ball stops exactly at the current node.
Now we start adding new long chains in batches.
Fix the maximum value $B$ for this scheme, choose $b\ge\lceil\sqrt d\rceil$, and set $h=B+1-b$.
Shift all the old auxiliary tree's colors up by $h$, so old nodes use $h,\ldots,B$. For the $j$-th new long chain in this batch, use:
- color $\lfloor j/b\rfloor$ for the chain head;
- color $h+(j\bmod b)$ for the second node;
- color $h$ for all remaining nodes.
This way, $bh=b(B+1-b)$ long chains can be added at once.
The key point is that a new chain head's color is smaller than $h$, while old nodes and the subsequent nodes of new chains all have colors at least $h$. So at any node, every newly attached chain is traversed before the original subsequent structure.
When parsing a new chain, we first read the chain head's small color, then recursively parse the other new chains hanging off that head. The large color read next is the color of that chain's second node. Together the two determine $j$, which determines which leaf the chain corresponds to and its length $\ell_i$. After that, parsing continues according to the known chain length.
Recognizing old-tree nodes is slightly more delicate. After reading the first color of an old child, we may first run into new chains hanging beneath it. We fully parse those new chains and stash their heads; then we peek at the first old child's color, use the pairs from before to identify the current old node, and attach the stashed new chains to it.
Here we cannot simply skip consecutive small colors and look for the next large color, because a new chain contains large colors internally. We must recursively consume the complete new-chain subtree. Scaffold::parse in the implementation handles exactly this.
So, given $d$ known long chains, a single round can advance the count of known long chains to any value up to $d+b(B+1-b)$.
3. Turn the singleton leaves into subset counting
Once all long chains are recovered, the internal skeleton of the whole tree is determined. The remaining $s$ unknown leaves each have only their parent left undetermined.
Now set $t=\lceil\sqrt D\rceil$, label the auxiliary tree with $t$ colors, and leave $q=B+1-t$ small colors.
Split the unknown leaves into at most $q$ groups of at most $g=\lceil s/q\rceil$ each, and assign one small color to each group. In each round we select a subset within each group and insert balls for it. After parsing the returned sequence, for every internal node and every group we obtain a number:
how many of the leaves selected this round have that internal node as their parent.
So each (internal node, leaf group) pair corresponds to an unknown binary vector $z$. We need to choose a binary matrix $A$ such that the integer vector $Az$ determines $z$ uniquely. This is the detecting matrix / search matrix problem from subset weighing. Note that we use integer counts here, not a linear system mod $2$. ([McGill School of Computer Science][1])
Below is a matrix that can be constructed and decoded directly, with no random search.
Define $W(r)=\sum_{a=1}^{r}\operatorname{popcount}(a)$. With $r$ rows we can distinguish $W(r)$ binary variables. For example, $W(7)=12$, $W(9)=15$, $W(11)=20$.
View integers as sets of bits. For each $a=1,\ldots,r$ and each $j=1,\ldots,\operatorname{popcount}(a)$, create a column. Let $R_{a,j}$ be the set of the lowest $j$ set bits of $a$, and define this column's value in row $x$ as
$$ A_{x,(a,j)} = [a\setminus R_{a,j}\subseteq x]\, [|x\cap R_{a,j}|\equiv1\pmod2], \qquad 1\le x\le r. $$
Take the smallest $r$ with $W(r)\ge g$ and keep the first $g$ columns. Each round, select leaves according to the corresponding row of the matrix; the selected leaves within one group all use the same color.
Here is the proof that this decodes uniquely.
View a column as a multilinear polynomial over boolean variables. It equals "the product of the variables in $a\setminus R_{a,j}$" times "the XOR of the variables in $R_{a,j}$". The leading coefficient of the XOR polynomial is $(-2)^{j-1}$, so the polynomial for this column contains only monomials that are subsets of $a$, and the coefficient of the monomial $a$ is exactly $(-2)^{j-1}$.
Now decode in the order $a=r,r-1,\ldots,1$, subtracting columns already solved from all observed values.
Adding the free value $y_0=0$, compute $z_a=\sum_{x\subseteq a}(-1)^{|a|-|x|}y_x$. This is the coefficient of the monomial $a$. The other columns not yet processed have support sets with numeric value smaller than $a$, so they cannot contain $a$ and contribute nothing to this coefficient. Hence $z_a=\sum_j\varepsilon_{a,j}(-2)^{j-1}$, where the $\varepsilon_{a,j}\in\{0,1\}$ are the variables to solve for in this step.
That is exactly a negabinary representation. Repeatedly take the nonnegative residue of the current number mod $2$ as the next digit, then subtract that digit and divide by $-2$; this recovers all the $\varepsilon_{a,j}$ uniquely.
Every $x\subseteq a$ used satisfies $x\le a\le r$, so no nonexistent observation row is ever referenced. Keeping only some of the columns does not affect uniqueness either — it just amounts to fixing the remaining variables to $0$.
So recovering all singleton leaves takes only the smallest $r$ with $qW(r)\ge s$.
4. Parameter choice, worst-case bound, and implementation
All costs can now be computed exactly.
The first collect has already used one round and recovered the first $8$ chains. With $B$ fixed, let $dp_B[d]$ be the minimum number of further rounds needed to get from the initial $a$ long chains to $d$ long chains.
The base case is $dp_B[a]=0$. In state $d$, enumerate $\lceil\sqrt d\rceil\le b\le B$; this round adds at most $b(B+1-b)$ long chains. Since we are free to add fewer, compute the maximum capacity and then update every reachable state.
Let $r_B$ be the number of rounds needed for the singleton-leaf phase: take $r_B=0$ when $s=0$; otherwise require $q=B+1-\lceil\sqrt D\rceil>0$ and take the smallest integer with $qW(r_B)\ge s$. The total cost satisfies $C\le B+1+dp_B[D]+r_B$.
Enumerate $8\le B\le27$ and pick the scheme with the smallest cost.
The conclusion $C\le28$ in the worst case comes from a complete finite parameter verification, not from random testing. It suffices to check all $(D,a)$ for $M=200$: $1\le D\le200$, $1\le a\le\min(8,D)$, and $s=200-D-8+a\ge0$ — $1544$ pairs in total.
For fixed $(D,a)$, a smaller $M$ only decreases $s$ and never increases the number of rounds needed, so this already covers every case with $M>8$. Exact enumeration gives:
| total long chains $D$ | worst minimum cost in the above range |
|---|---|
| $1\le D\le36$ | $27$ |
| $37\le D\le140$ | $28$ |
| $141\le D\le200$ | $27$ |
For example, with $M=200,D=37,a=8$ one can take $B=17$: one round recovers the remaining long chains; there are $163$ singleton leaves, with $t=7,q=11,g=15$, recovered in $9$ rounds. In total $K=1+1+9=11$, so $C=28$.
The number of ball insertions is also far below the limit. The first pass has $N$ successes and $M$ failures, and afterwards each round places at most one ball per node. Since $B\ge8$ and $C\le28$, we have $K\le20$, so the total number of calls is at most $KN+M\le20200$, while the problem allows $500000$.
The implementation contains no exponential search. Processing the auxiliary tree each round is $O(N\log M)$; decoding the detecting matrix per group is $O(r^2+rg)$, where the total number of subset enumerations is also $O(r^2)$. All of these parameters are tiny for this problem.
Code at https://qoj.ac/submission/2952241 .