USACO Silver 2016 February - Load Balancing

Authors: Benjamin Qi, Kevin Sheng, Varun Ragunath

Official Analysis (Java)

Video Solution

By Varun Ragunath

Video Solution Code

Solution 1

Similar to the analysis.

Time Complexity: O(N2)\mathcal{O}(N^2)

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];

Python

from typing import List, Tuple
with 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: O(N3)\mathcal{O}(N^3)

The solution to the Bronze version of this problem runs in O(N3)\mathcal O(N^3) 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 xx and yy-coordinates that are close to the median xx or yy, respectively. This would improve the time complexity to O(N)\mathcal O(N). However, such a solution cannot be correct. For example, consider the case where N=999N=999 and xi=yi=2i1x_i=y_i=2i-1. Then M=333M=333, and the xx and yy coordinates we need to select to obtain this MM are rather far away from their respective medians.

Nevertheless, we can still speed up the Bronze solution by a constant factor by checking fewer xx and yy coordinates. Note that if we increase the xx-coordinate of the north-south fence by two and there are still at most N3\frac{N}{3} cows to the left of the fence, then MM stays the same or decreases. Thus, we can reduce the number of xx-coordinates we need to check to N3+O(1)\frac{N}{3}+\mathcal O(1). Similarly, the number of yy-coordinates we need to check is also N3+O(1)\frac{N}{3}+\mathcal O(1). 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];

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!