Editorial
Every cutting process corresponds to a full binary tree whose leaf order is fixed. An internal node's boundary is red exactly when the interval represented by that node has odd length.
Tracking the number of current odd-length pieces gives the possible number of red cuts:
- If , then .
- If , then .
For an odd interval of length , call the following sets certificate blocks:
Induction shows that every feasible red-boundary set contains a complete certificate block. Conversely, the following conditions are sufficient:
- For length , every boundary set of size at most is feasible.
- For length , every set of size between and that contains a certificate block is feasible.
Sufficiency follows by strong induction, choosing the first cut so the remaining requirements split into smaller even and odd intervals.
If is even, choose the cheapest boundaries. If is odd, enumerate a forced certificate block and add the cheapest boundaries outside . After sorting costs, store prefix sums and each boundary's rank. Since a block has at most two elements, each candidate is evaluated in .
The total time complexity is and the memory complexity is .
Solution written by GPT5