Video Solution
By Vikas Thoutam
Video Solution Code
Explanation
We start with our list of heights and make a sorted copy of it. Then we compare the original list to the sorted list, keeping track of at which positions where they differ.
Because removing exactly one cow must make the list sorted, those out-of-place cows form a sequence which is sorted except for one element, so it takes exactly moves to put everyone back in order (and if , we need zero moves).
Implementation
Time Complexity:
with open("outofplace.in") as read:cow_num = int(read.readline())cows = [int(read.readline()) for _ in range(cow_num)]sorted_order = sorted(cows)# The number of cows that are out of place relative to the sorted orderbad_num = 0for i in range(len(cows)):if cows[i] != sorted_order[i]:bad_num += 1print(bad_num - 1, file=open("outofplace.out", "w"))
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!