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

The Small Castle Built by a Dwarf

Back to problem

Editorial

Let Fi(h)F_i(h)Fi​(h) be the minimum cost for the first iii castles when the last height is hhh. Then

Fi(h)=costi(h)+min⁡(Fi−1(h−1),Fi−1(h+1)).F_i(h)=\mathrm{cost}_i(h)+\min(F_{i-1}(h-1),F_{i-1}(h+1)).Fi​(h)=costi​(h)+min(Fi−1​(h

Separate heights by parity and write h=2x+ph=2x+ph=2x+p. For each parity, FiF_iFi​ is a discrete convex function. Taking the minimum of the two neighboring previous states becomes a length-one sliding minimum of a convex function, which is supported by shifting the two lazy offsets in slope trick.

The adjustment cost is convex as well. If Hi−pH_i-pHi​−p is even, add two asymmetric V-functions at the same vertex. If it is odd, add one at each of two neighboring vertices. This reproduces the exact cost on h=2x+ph=2x+ph=2x+p. Enforce positive heights using a lower-bound penalty whose weight is larger than the sum of all genuine cost slopes.

A weighted two-heap slope-trick structure processes every breakpoint in logarithmic time. The total complexity is O(Nlog⁡N)O(N\log N)O(NlogN). Use 128-bit integers for costs.

−
1),Fi−1​(h+
1)).