USACO Silver 2019 February - Sleepy Cow Herding

Authors: Qi Wang, Melody Yu

Official Analysis (C++)

Video Solution

By Melody Yu

Note: The video solution might not be the same as other solutions. Code in C++.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N \log N)

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("herding.in", "r", stdin);
int n;
cin >> n;
vector<int> herd(n);
for (int i = 0; i < n; ++i) { cin >> herd[i]; }

Java

import java.io.*;
import java.util.*;
public class Herding {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("herding.in"));
int n = Integer.parseInt(br.readLine());
int[] herd = new int[n];
for (int i = 0; i < n; i++) {

Python

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 = 2
elif herd[n - 1] - herd[1] == n - 2 and herd[1] - herd[0] > 2:
min_moves = 2
else:

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!