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

Bulb Queries

Back to problem

Editorial

Consider a query interval [l,r][l,r][l,r]. Every contiguous group of bulbs that are on has exactly one left endpoint. Therefore, the number of groups equals the number of positions that are left endpoints of groups.

For each i∈[l,r]i \in [l,r]i∈[l,r], define the indicator random variable XiX_iXi​ to be 111 if bulb iii is the left endpoint of a group and 000 otherwise.

At the first position of the interval, the bulb to its left is ignored, so

E[Xl]=Pl.\mathbb{E}[X_l]=P_l.E[Xl​]=Pl​.

For i>li>li>l, bulb iii must be on and bulb i−1i-1i−1 must be off. By independence,

E[Xi]=Pi(1−Pi−1).\mathbb{E}[X_i]=P_i(1-P_{i-1}).E[Xi​]=Pi​(1−P

By linearity of expectation, the answer is

Pl+∑i=l+1rPi(1−Pi−1).P_l+\sum_{i=l+1}^{r} P_i(1-P_{i-1}).Pl​+i=l+1∑r​

For every 2≤i≤N2 \le i \le N2≤i≤N, precompute

Ai=Pi(1−Pi−1),A_i=P_i(1-P_{i-1}),Ai​=Pi​(1−P

and let Si=∑j=2iAjS_i=\sum_{j=2}^{i}A_jSi​=∑j=2i​A. Then each query is answered in time as

Pl+Sr−Sl.P_l+S_r-S_l.Pl​+Sr​−Sl​

The preprocessing takes O(N)O(N)O(N) time, all queries take O(Q)O(Q)O(Q) time, and the memory usage is O(N)O(N)O(N).

Because each input probability has at most two digits after the decimal point, it can be converted to an integer from 000 to 100100100. This makes every intermediate value exact. Using double is also sufficient, but float is unsafe because the maximum answer can be about 25 00025\ 00025 000.

Solution written by GPT5.6

i−1​
)
.
Pi​
(
1
−
Pi−1​).
i−1
​
)
,
j
​
O(1)O(1)O(1)
.