Editorial
Let be the minimum and maximum crop rows and columns.
Initially, the machine occupies only row . Harvesting crops in both rows and requires its row segment to contain , , and . Thus, at least extensions are needed.
The machine must also visit both columns and . Visit one endpoint first and then the other; choose the shorter of the two orders. The minimum number of moves is
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 . Use the general formula for the full subtask.
The time complexity is per case and overall. The extra space complexity is .
Solution written by GPT5