DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

N rooms

Back to problem

Editorial

Let P=p0+p1+⋯+pNP=p_0+p_1+\cdots+p_NP=p0​+p1​+⋯+pN​. Let EiE_iEi​ be the expected total time spent in room iii before the process ends, and define EN+1=0E_{N+1}=0EN+1​=0.

For door iii, let RiR_iRi​ be the number of crossings from left to right and LiL_iLi​ the number of crossings from right to left. Ddas starts to the left of door ii and finishes to its right, so every execution satisfies

Ri−Li=1.R_i-L_i=1.Ri​−Li​=1.

During each minute spent in room iii, Ddas crosses door iii to the right with probability piP\frac{p_i}{P}Ppi​​. Hence

E[Ri]=EipiP.\mathbb E[R_i]=E_i\frac{p_i}{P}.E[Ri​]=Ei​P

Similarly,

E[Li]=Ei+1piP.\mathbb E[L_i]=E_{i+1}\frac{p_i}{P}.E[Li​]=Ei+1​P

Subtracting gives

(Ei−Ei+1)piP=1,(E_i-E_{i+1})\frac{p_i}{P}=1,(Ei​−Ei+1​)P

and therefore

Ei−Ei+1=Ppi.E_i-E_{i+1}=\frac{P}{p_i}.Ei​−Ei+1​=

Summing this identity from iii through NNN and using EN+1=0E_{N+1}=0EN+1​=0 gives

Ei=P∑k=iN1pk.E_i=P\sum_{k=i}^{N}\frac{1}{p_k}.Ei​=Pk=i∑N​

Thus, after computing the modular inverses of all pip_ipi​, all answers can be obtained by maintaining a suffix sum of the inverses.

Computing every inverse separately with Fermat's little theorem takes O(Nlog⁡998244353)O(N\log 998244353)O(Nlog998244353) 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 O(N+log⁡998244353)O(N+\log 998244353)O(N+log998244353) time.

Solution written by GPT5.6

i
pi​
​
.
pi​
​
.
pi​
​
=
1,
pi​
P
​
.
pk​1​
.