Editorial
Let . Let be the expected total time spent in room before the process ends, and define .
For door , let be the number of crossings from left to right and the number of crossings from right to left. Ddas starts to the left of door and finishes to its right, so every execution satisfies
During each minute spent in room , Ddas crosses door to the right with probability . Hence
Similarly,
Subtracting gives
and therefore
Summing this identity from through and using gives
Thus, after computing the modular inverses of all , all answers can be obtained by maintaining a suffix sum of the inverses.
Computing every inverse separately with Fermat's little theorem takes time. The reference solution instead uses batch inversion: it builds prefix products, computes the inverse of the total product once, and proceeds backward. This takes time.
Solution written by GPT5.6