# Old yd and Disjoint Sets: Solution Problem setter's solution: enumerate the two step counts of terminating paths and count their orderings with binomial coefficients. Codex (GPT-6) contributed exact rational bounds, smaller modular tables, proofs and the standard C++17 implementation. Binomial counting, factorial inverses and the neighboring-fraction denominator lemma are classical methods. ## Expand until the threshold is first crossed For one query, write $t=n-B\ge0$ . A path with $a$ unit steps and $b$ steps of length $e$ contributes $A C^aD^b$ at its leaf. It terminates exactly when $$a+eb>t,$$ while removing its last step leaves a total decrement at most $t$ . Since every step is positive, validity of this penultimate position also makes all earlier positions valid. ![Expansion into two leaves for query three](assets/explanation.svg) The diagram shows $n=3$ in the first sample. Both leaves have value one, with weights seven and four. For $b=0$ , only $a=t+1$ is possible, contributing $C^{t+1}$ before the final multiplication by $A$ . For $b\ge1$ , define $$L_b=\max(0,t-\lfloor eb\rfloor),\qquad R_b=\begin{cases}t,&b=1,\\t-\lfloor e(b-1)\rfloor-1,&b>1.\end{cases}$$ The terminal condition gives $a\ge L_b$ . If the final step has length $e$ , the penultimate condition $a+e(b-1)\le t$ gives $a\le R_b$ . The case $b=1$ needs its integer boundary handled separately. Once $R_b<0$ , larger $b$ cannot contribute and enumeration stops. For $a=L_b>0$ , either kind of final step is possible. Their counts sum to $$\binom{a+b-1}{a-1}+\binom{a+b-1}{a}=\binom{a+b}{a}.$$ When $L_b=0$ , the final step must have length $e$ , but its count is still $\binom b0=1$ . For $a>L_b$ , only a final step of length $e$ is valid, giving $\binom{a+b-1}{a}$ orderings. Hence the answer is $$A\left(C^{t+1}+\sum_{b\ge1:R_b\ge0}D^b\left[\binom{L_b+b}{L_b}C^{L_b}+\sum_{a=L_b+1}^{R_b}\binom{a+b-1}{a}C^a\right]\right)\pmod{10^9+7}.$$ Successive values of $\lfloor eb\rfloor$ differ by two or three, so each $b$ needs at most three values of $a$ . ## Compute floors exactly with integers Floating-point rounding should not determine whether a leaf has crossed the threshold. Use the strict bounds $$\frac{410105312}{150869313}