sweet1cris

Untitled

Jan 8th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. public class HotelStops {
  2.     /**
  3.      * input = { 190, 420, 550, 660, 670 };
  4.      * penalties = {0, 100, 1000, 5900, 2600, 3500};
  5.      * prev = {-1, 0, 1, 2, 2, 2);
  6.      * result = {1, 2, 5} stop at 190, 420, 670
  7.      * To recover the path from minimum penalties, while
  8.      * computing penalties[i], we also note down prev[i],
  9.      * the next to last stop on the minimum stop to i
  10.      */
  11.     public static List<Integer> hotelStops(int[] input) {
  12.         List<Integer> result = new ArrayList<Integer>();
  13.         int[] penalties = new int[input.length + 1];
  14.         int[] prev = new int[input.length + 1];
  15.         penalties[0] = 0;
  16.         prev[0] = -1;
  17.         for (int i = 1; i < penalties.length; i++) {
  18.             penalties[i] = (int) Math.pow(200 - input[i - 1], 2);
  19.             prev[i] = 0;
  20.             for (int j = 1; j < i; j++) {
  21.                 int cur = penalties[j] + (int) Math.pow(200 - (input[i - 1] - input[j - 1]), 2);
  22.                 if (cur < penalties[i]) {
  23.                     penalties[i] = cur;
  24.                     prev[i] = j;
  25.                 }
  26.             }
  27.         }
  28.         System.out.println(Arrays.toString(penalties));
  29.         System.out.println(Arrays.toString(prev));
  30.         int idx = prev.length - 1;
  31.         while (prev[idx] != -1) {
  32.             result.add(idx);
  33.             idx = prev[idx];
  34.         }
  35.         Collections.reverse(result);
  36.         System.out.println(result);
  37.         return result;
  38.     }
  39.     public static void main(String[] args) {
  40.         int[] input = { 190, 420, 550, 660, 670 };
  41.         HotelStops.hotelStops(input);
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment