USACO Silver 2016 February - Load Balancing
Authors: Benjamin Qi, Kevin Sheng, Varun Ragunath
Video Solution
By Varun Ragunath
Video Solution Code
Solution 1
Similar to the analysis.
Time Complexity:
C++
#include <algorithm>#include <fstream>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;struct Cow {
Java
import java.io.*;import java.util.*;public class Balancing {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new FileReader("balancing.in"));int cowNum = Integer.parseInt(read.readLine());// The array of cows (to be sorted by x-pos)int[][] byX = new int[cowNum][2];for (int c = 0; c < cowNum; c++) {
Python
from typing import List, Tuplewith open("balancing.in") as read:# The array of cows (to be sorted by x-pos)by_x = []for _ in range(int(read.readline())):by_x.append(tuple(int(i) for i in read.readline().split()))
Solution 2
Time Complexity:
The solution to the Bronze version of this problem runs in time, but is not fast enough to pass the Silver version. One way to speed up the Bronze solution is to check only a constant number of and -coordinates that are close to the median or , respectively. This would improve the time complexity to . However, such a solution cannot be correct. For example, consider the case where and . Then , and the and coordinates we need to select to obtain this are rather far away from their respective medians.
Nevertheless, we can still speed up the Bronze solution by a constant factor by checking fewer and coordinates. Note that if we increase the -coordinate of the north-south fence by two and there are still at most cows to the left of the fence, then stays the same or decreases. Thus, we can reduce the number of -coordinates we need to check to . Similarly, the number of -coordinates we need to check is also . This reduces the number of operations in the Bronze solution by a factor of 9, which is enough to pass the Silver version.
C++
#include <algorithm>#include <fstream>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;struct Cow {
Java
import java.io.*;import java.util.*;public class Balancing {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new FileReader("balancing.in"));int cowNum = Integer.parseInt(read.readLine());int[][] cows = new int[cowNum][2];int[] xPos = new int[cowNum];
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!