I’m doing Load Balancing from the 2016 February contest.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("balancing.in");
Scanner reader = new Scanner(inputFile);
PrintWriter writer = new PrintWriter("balancing.out");
int n = reader.nextInt();
int b = reader.nextInt();
ArrayList<Integer> xVals = new ArrayList<>();
ArrayList<Integer> yVals = new ArrayList<>();
int maxXVal = 0;
int maxYVal = 0;
for (int i = 0; i < n; i++) {
int xVal = reader.nextInt();
xVals.add(xVal);
if (xVal > maxXVal) maxXVal = xVal;
int yVal = reader.nextInt();
yVals.add(yVal);
if (yVal > maxYVal) maxYVal = yVal;
}
int minMax = findMax(0, 0, xVals, yVals);
for (int x = 0; x < maxXVal; x += 2) {
if (xVals.contains(x - 1) && x >= 2) {
for (int y = 2; y < maxYVal; y += 2) {
if (yVals.contains(y - 1)) {
int max = findMax(x, y, xVals, yVals);
if (max < minMax) minMax = max;
}
}
} else if (x == 0) {
for (int y = 2; y < maxYVal; y += 2) {
if (yVals.contains(y - 1)) {
int max = findMax(x, y, xVals, yVals);
if (max < minMax) minMax = max;
}
}
}
}
writer.println(minMax);
writer.close();
reader.close();
}
static int findMax(int a, int b, ArrayList<Integer> xVals, ArrayList<Integer> yVals) {
int quadrant1 = 0;
int quadrant2 = 0;
int quadrant3 = 0;
int quadrant4 = 0;
for (int i = 0; i < xVals.size(); i++) {
int x = xVals.get(i);
int y = yVals.get(i);
if (x > a) {
if (y > b) {
quadrant1++;
} else {
quadrant4++;
}
} else {
if (y > b) {
quadrant2++;
} else {
quadrant3++;
}
}
}
return Math.max(Math.max(quadrant1, quadrant2), Math.max(quadrant3, quadrant4));
}
Initially, I got the first 6 test cases correct and the last 4 timed out. However, after researching a bit, I got 9 test cases right, with only the last one timing out. I implemented what I understood of the sweep line algorithm, but I wanted to know how I could make my code efficient enough for the last test case.