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

Imp 2

Back to problem

Editorial

1. Representing a strategy as an order

If the imp does not cast a spell after a purchase, the game ends immediately. Therefore, the only continuation branch is that the just-bought item is destroyed. A strategy can consequently be represented by an order of distinct boxes.

Fix a positive target profit xxx. Since the imp may destroy the first kkk bought items, guaranteeing an obtained item requires planning k+1k+1k+1 boxes. For an order p1,p2,…,pk+1p_1,p_2,\ldots,p_{k+1}p1​,p2​,…,pk+1​, if the first surviving item is pip_ipi​, the required condition is

∑j=1icpj≤vpi−x\sum_{j=1}^{i} c_{p_j} \le v_{p_i}-xj=1∑i​cpj​

for every 1≤i≤k+11 \le i \le k+11≤i≤k+1.

Profit 000 is always available by leaving immediately.

2. Scheduling reduction

For a fixed xxx, create one job for each box with processing time cic_ici​ and deadline vi−xv_i-xvi​−x. The condition above asks for at least jobs that can all finish by their deadlines.

3. Maximum number of on-time jobs

Process jobs in nondecreasing deadline order. Insert each processing time into a max-heap and add it to the current total. If the total exceeds the current deadline, remove the largest processing time.

After every prefix, the heap contains a maximum-cardinality feasible subset, and among such subsets it has minimum total processing time. Removing the longest selected job is exactly the exchange that preserves this invariant.

The target xxx is feasible if and only if the final heap size is at least k+1k+1k+1.

Because deadlines are vi−xv_i-xvi​−x, their relative order is the same as the order of viv_ivi​ for every xxx, so the items need to be sorted only once.

4. Binary search

Feasibility is monotone in xxx. The answer lies between 000 and 1 000 0001\ 000\ 0001 000 000, so binary-search this range.

A feasibility check costs O(nlog⁡n)O(n\log n)O(nlogn). The total time complexity is

O(nlog⁡nlog⁡1 000 001),O(n\log n\log 1\ 000\ 001),O(nlognlog1 000 001),

with O(n)O(n)O(n) memory.

Solution written by GPT5.6

​
≤
vpi​​−
x
k+1k+1
k+1