On USACO : Milking Cows or Milk2 problem

by


Take a look at the problem statement before reading on.

The following is a seriously wrong way to implement this problem. I went for too much storage.
But I think it has enforced in my mind the importance of considering global vs local optima.
One of the corner test cases, aptly called bad data, forces you to consider not just consecutive entries, but also look at the overall picture.

Note to myself: Need to stop making so many off by one errors.

/*
ID: abhi
LANG: JAVA
TASK: milk2
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;


public class milk2
{
public static void main(String[] args) throws NumberFormatException, IOException
{
// int[] start = new int[] {2,4,6,8 ,10,12,14,16,18,1};
// int[] end = new int[]   {3,5,7,9 ,11,13,15,17,19,20};

// int[] start = new int[] {100,201,302,403};
// int[] end = new int[]   {200,301,402,503};

// int[] start = new int[] {10,21,32,43};

// int[] end = new int[]   {20,31,42,53};

BufferedReader reader = new BufferedReader(new FileReader(new File("milk2.in")));
int count = Integer.parseInt(reader.readLine());
int[] start = new int[count];
int[] end = new int[count];
for(int i=0;i<count;i++) {
StringTokenizer tok = new StringTokenizer(reader.readLine());
start[i] = Integer.parseInt(tok.nextToken());
end[i] = Integer.parseInt(tok.nextToken());
}


sortTogether(start, end);
int begin= start[0];
sortTogether(end, start);
int ending = end[end.length-1];

boolean[] store = new boolean[ending+1];
Arrays.fill(store, false);

sortTogether(start, end);
for(int i=0;i<start.length;i++) {
System.out.println(start[i] + " and " + end[i]);
for(int j=start[i]+1;j<=end[i];j++) {

store[j]=true;
// System.out.println(j + " is " + store[j]);
}
}
int longestPeriod=0;
int currentLength=0;
for(int i=begin+1;i<=ending;i++) {
currentLength = store[i] ? currentLength+1 : 0;
longestPeriod = (currentLength>longestPeriod) ? currentLength :longestPeriod;
}
PrintWriter out = new PrintWriter(new File("milk2.out"));
// System.out.println("Longest busy" + (longestPeriod));
out.print(longestPeriod + " ");

longestPeriod=0;
currentLength=0;
for(int i=begin+1;i<=ending;i++) {
currentLength = (!store[i]) ? currentLength+1 : 0;
longestPeriod = (currentLength>longestPeriod) ? currentLength :longestPeriod;
}
System.out.println("Longest idle" + (longestPeriod));
out.println(longestPeriod);
out.close();
System.exit(0);
}

static void sortTogether(int[] start, int[] end) {
int temp=0;
for(int i=0;i<start.length;i++) {
for(int j=i;j<start.length;j++) {
if(start[i]>start[j]) {
temp=start[i];
start[i]=start[j];
start[j]=temp;

temp=end[i];
end[i]=end[j];
end[j]=temp;
}
}
}
}
}