Let be 1 if person initially faces right and 0 otherwise. Define the final-direction indicator similarly. Let be their total left and right departures. Alternation implies .
Put and let be the number of sticks discarded to the left. Conservation across each edge gives , with and . Consequently,
Since , both and the final number of right-facing people are determined.
Scan from left to right, maintaining and the remaining number of right-facing final directions. Set precisely when , , and , and decrement . Otherwise set . Update and . The answer is .
To justify the greedy choice, put , , and . Nonnegative departures are equivalent to
Because is nondecreasing, first increases and then decreases, ending at the required total number of final right directions. Thus taking a feasible 1 as early as possible, while respecting this total, never violates a later upper bound. Comparing prefixes against any feasible final state shows that greedy never chooses its 1s later, so it reaches the required total. All departures are nonnegative and the boundary conditions hold.
It remains to show these counts describe a legal execution. A fired person's last departure is opposite their final direction. On a path, a directed last-departure cycle could only be two neighbors whose final directions are left, right. If greedy creates this transition, or , implying one endpoint never fires. Hence there is no last-departure cycle among fired people.
Any legal execution cannot exceed the computed quota at a vertex: at the first excess firing, neighbors have sent at most their quotas, so conservation leaves no stick there. If an execution finished with unused quotas, the remaining departures would be balanced at each vertex and send no stick to a sink. Following their last departures would create a directed cycle, a contradiction. Therefore every legal execution has exactly these counts, and their sum is the minimum.
The time and space complexities are . Use signed 64-bit integers. For , we have , giving the safe answer bound .
Solution written by GPT6.1