Video Solution 1
By Hannah Ying
Note: The video solution might not be the same as other solutions. Code in C++.
Video Solution 2
By Melody Yu
Note: The video solution might not be the same as other solutions. Code in C++.
Video Solution Code
Solution
Explanation
Minimum
We will generally use a two-pointer sliding window technique on the sorted cows array to find the window containing the most cows (i.e fewest empty spaces). The minimum value is the number of empty spaces in that window. However, there is an edge case: if cows are already consecutive but the last cow is far away, we need moves instead of since we have to bridge the gap first.
Maximum
It is similar to the bronze version of this problem. We will consider the total number of empty cells between all cows, then subtract the gap we want to sacrifice. Here, the gaps are and . To get the maximum value, we sacrifice the smaller of the two gaps.
Implementation
Time Complexity:
with open("herding.in") as read:n = int(read.readline())herd = sorted(int(read.readline()) for _ in range(n))min_moves = float("inf")if herd[n - 2] - herd[0] == n - 2 and herd[n - 1] - herd[n - 2] > 2:min_moves = 2elif herd[n - 1] - herd[1] == n - 2 and herd[1] - herd[0] > 2:min_moves = 2else:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!