DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
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 account linking.

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

Treasure Hunt

Back to problem

Editorial

Let dp[i][0]dp[i][0]dp[i][0] be the maximum searched length after choosing directions for people 111 through iii, with person iii facing left. Let dp[i][1]dp[i][1]dp[i][1] be the corresponding maximum when person iii faces right.

For convenience, set

A0=B0=0,AN+1=L,BN+1=0.A_0=B_0=0,\qquad A_{N+1}=L,\qquad B_{N+1}=0.A0​=B0​=0,A

The initial values are dp[0][0]=dp[0][1]=0dp[0][0]=dp[0][1]=0dp[0][0]=dp[0][1]=0.

Suppose person iii faces left. If person i−1i-1i−1 also faces left, the newly covered length is min⁡(Ai−Ai−1,Bi)\min(A_i-A_{i-1},B_i)min(Ai​−.

If person i−1i-1i−1 faces right, person i−1i-1i−1 may already cover up to Bi−1B_{i-1}Bi−1​ units of the gap between the two people. The uncovered part of that gap therefore has length , so person can newly cover

min⁡(Bi,max⁡(0,Ai−Ai−1−Bi−1))\min(B_i,\max(0,A_i-A_{i-1}-B_{i-1}))min(Bi​,max(0,Ai​−

units.

Thus,

dp[i][0]=max⁡(dp[i−1][0]+min⁡(Ai−Ai−1,Bi),dp[i−1][1]+min⁡(Bi,max⁡(0,Ai−Ai−1−Bi−1))).dp[i][0]=\max\left( dp[i-1][0]+\min(A_i-A_{i-1},B_i), dp[i-1][1]+\min(B_i,\max(0,A_i-A_{i-1}-B_{i-1})) \right).dp[i][0]=

If person iii faces right, the newly searched interval does not overlap any previously searched interval by a positive length. Therefore,

dp[i][1]=max⁡(dp[i−1][0],dp[i−1][1])+min⁡(Ai+1−Ai,Bi).dp[i][1]=\max(dp[i-1][0],dp[i-1][1])+\min(A_{i+1}-A_i,B_i).dp[i][1]=max(dp[i−1][0]

The answer is max⁡(dp[N][0],dp[N][1])\max(dp[N][0],dp[N][1])max(dp[N][0],dp[N][1]). Each transition takes constant time, so the time complexity is O(N)O(N)O(N).

Solution written by GPT5.6

N+1​
=
L,BN+1​=
0.
A
i−1​
,
Bi​
)
max⁡(0,Ai−Ai−1−Bi−1)\max(0,A_i-A_{i-1}-B_{i-1})
max(0,Ai​−Ai−1​−Bi−1​)
iii
A
i−1​
−
Bi−1​))
max(dp[i−1][0]+min(Ai​−Ai−1​,Bi​),dp[i−1][1]+min(Bi​,max(0,Ai​−Ai−1​−Bi−1​))).
,
d
p
[
i
−
1][1])+
min(Ai+1​−
Ai​,Bi​).