Editorial for UTS Open '24 P1 - Watering the Plants


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: Sucram314

Subtask 1

Since K = 1, Marcus' watering can only holds one unit of water. Thus, he must walk back to position 0 to refill his watering can every time he waters a flower. The distance Marcus needs to travel to water flower i and return to position 0 is i + i = 2i. So, the minimum total distance Marcus needs to travel to water all the flowers is:


\begin{gather*}
2 \times (1 + 2 + 3 + \dots + N) = N(N+1)
\end{gather*}

In python terms, the answer is 2*sum(range(1, N+1))

Since N is quite small, this can either be calculated with a loop, or with the simplified formula.

Time Complexity: \mathcal{O}(N) or \mathcal{O}(1)

Subtask 2

Since K might be greater than 1, we must consider how to water multiple plants in one trip to minimize the walking distance. The critical observation to solve this problem is to realize that in any given moment, the furthest K flowers should always be watered together, since that reduces the maximum distance that Marcus has to walk in a future trip the most. Thus, we can group the flowers into blocks of K starting from the rightmost flower, and perform trips forward and back, similarly to Subtask 1. Note that the leftmost block of flowers may contain less than K flowers.

For example, if there are N = 5 flowers and Marcus' watering can holds K = 2 units of water, he should first water plants 4 and 5, then plants 2 and 3, and finally plant 1. In total, he will walk 5 + 5 + 3 + 3 + 1 + 1 = 18 units of distance.

In python terms, the answer is 2*sum(range(N, 0, -K))

Since N is quite small, this can be calculated with a loop.

Time Complexity: \mathcal{O}\left(\frac NK\right)

Bonus

Python golf solution (49 bytes): https://dmoj.ca/src/6848690

It is possible to solve this question in \mathcal{O}(1) time.

In total, there will be B = \left\lceil \frac NK \right\rceil blocks of K flowers. The distance Marcus needs to travel to water the ith block from the right and return to position 0 is 2 \times \Big(N - (i-1)K\Big). Thus, the minimum total distance is:


\begin{gather*}
2 \times \bigg[N + (N - K) + (N - 2K) + \dots + \Big(N - (B - 1) K\Big)\bigg] = 2NB - KB(B-1)
\end{gather*}

Tip: you can perform ceiling division of positive integers using floor division! \left\lceil \frac NK \right\rceil = \left\lfloor \frac{N + K -1}K \right\rfloor

Time Complexity: \mathcal{O}(1)


Comments

There are no comments at the moment.