USACO Bronze 2018 January - Out of Place

Authors: Maggie Liu, Ryan Chou, Vikas Thoutam

Official Analysis (Java)

Video Solution

By Vikas Thoutam

Video Solution Code

Implementation

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

C++

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main() {

Java

import java.io.*;
import java.util.*;
public class OutOfPlace {
public static void main(String[] args) throws IOException {
BufferedReader read =
new BufferedReader(new FileReader("outofplace.in"));
int cowNum = Integer.parseInt(read.readLine());
int[] cows = new int[cowNum];
for (int c = 0; c < cowNum; c++) {

Python

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 order
bad_num = 0
for i in range(len(cows)):
if cows[i] != sorted_order[i]:
bad_num += 1
print(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!