alefhidalgo

GasStations

Jun 20th, 2011
1,132
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Scanner;
  4.  
  5. /**
  6.  * Tuenti Programming Contest
  7.  * Challenge 11: Gas stations
  8.  * @author alefhidalgo [at] gmail [dot] com
  9.  */
  10. public class GasStations {
  11.      
  12.     public static final String NO_STOPS = "No stops";
  13.  
  14.     public String calculateGasStations(long autonomy, long totalDistanceToTravel, List<Long> distances) {
  15.         if (autonomy >= totalDistanceToTravel) {
  16.             return GasStations.NO_STOPS;
  17.         }
  18.         StringBuilder sbfGasStation = new StringBuilder();
  19.         if(distances.size() == 1){
  20.             return String.valueOf(distances.get(0));
  21.         }      
  22.         long lastDistance = 0;
  23.         for (int i = 1; i < distances.size(); i++) {
  24.             if ((distances.get(i) - lastDistance) > autonomy) {
  25.                 sbfGasStation.append((sbfGasStation.length() > 0 ? " " : "") + distances.get(i - 1));
  26.                 lastDistance = distances.get(i - 1);
  27.                 if ((lastDistance + autonomy) >= totalDistanceToTravel) {
  28.                     break;
  29.                 }
  30.             }
  31.         }
  32.         return sbfGasStation.toString();
  33.     }
  34.  
  35.     public static void main(String args[]) {
  36.         GasStations gasStations = new GasStations();
  37.         long autonomy;
  38.         long totalDistanceToTravel;
  39.         List<Long> distances;
  40.         Scanner in = new Scanner(System.in);
  41.         Scanner lineScanner = null;
  42.         int nCases = Integer.parseInt(in.nextLine().trim());
  43.         for (int i = 0; i < nCases; i++) {
  44.             autonomy = Integer.parseInt(in.nextLine().trim());
  45.             totalDistanceToTravel = Integer.parseInt(in.nextLine().trim());
  46.             int totalDistances = Integer.parseInt(in.nextLine().trim());
  47.             distances = new ArrayList<Long>(totalDistances);
  48.             lineScanner = new Scanner(in.nextLine());
  49.             for (int j = 0; j < totalDistances; j++) {
  50.                 distances.add(lineScanner.nextLong());
  51.             }
  52.             System.out.println(gasStations.calculateGasStations(autonomy, totalDistanceToTravel, distances));
  53.         }
  54.     }
  55. }
RAW Paste Data