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

Harvesting the Farm

Back to problem

Editorial

Let ymin⁡,ymax⁡,xmin⁡,xmax⁡y_{\min},y_{\max},x_{\min},x_{\max}ymin​,ymax​,xmin​,xmax​ be the minimum and maximum crop rows and columns.

Initially, the machine occupies only row SrS_rSr​. Harvesting crops in both rows ymin⁡y_{\min}ymin​ and ymax⁡y_{\max}y requires its row segment to contain , , and . Thus, at least extensions are needed.

The machine must also visit both columns xmin⁡x_{\min}xmin​ and xmax⁡x_{\max}xmax​. Visit one endpoint first and then the other; choose the shorter of the two orders. The minimum number of moves is

(xmax⁡−xmin⁡)+min⁡(∣Sc−xmin⁡∣,∣Sc−xmax⁡∣).(x_{\max}-x_{\min})+\min(|S_c-x_{\min}|,|S_c-x_{\max}|).(xmax​−xmin​

Extend the machine at its initial column until it covers every crop row. Then move to the nearer endpoint column and traverse to the other endpoint. The machine covers every crop during this process. Hence, both lower bounds are achieved simultaneously, and their sum is the answer.

Subtask 1 needs only the vertical extension cost because every crop is in the starting column. Subtask 2 needs only the horizontal movement cost because every crop is in the starting row. In subtask 3, every crop is in or to the right of the starting column, so the horizontal movement cost is xmax⁡−Scx_{\max}-S_cxmax​−Sc​. Use the general formula for the full subtask.

The time complexity is O(N)O(N)O(N) per case and O(T+∑N)O(T+\sum N)O(T+∑N) overall. The extra space complexity is O(1)O(1)O(1).

Solution written by GPT5

max​
SrS_rSr​
ymin⁡y_{\min}ymin​
ymax⁡y_{\max}ymax​
max⁡(Sr,ymax⁡)−min⁡(Sr,ymin⁡)\max(S_r,y_{\max})-\min(S_r,y_{\min})max(Sr​,ymax​)−min(Sr​,ymin​)
)
+
min(∣Sc​−
xmin​∣,∣Sc​−
xmax​∣).