Advertisement
sweet1cris

Untitled

Sep 25th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. public class CuttingWoodI {
  2.   public int minCost(int[] cuts, int length) {
  3.     // Assumptions: cuts is not null, length >= 0, all cuts are valid numbers.
  4.     // First we need to pad the original array at leftmost and
  5.     // rightmost position.
  6.     int[] helper = new int[cuts.length + 2];
  7.     helper[0] = 0;
  8.     for (int i = 0; i < cuts.length; i++) {
  9.       helper[i + 1] = cuts[i];
  10.     }
  11.     helper[helper.length - 1] = length;
  12.     // minCost[i][j]: the min cost of cutting the partition(i,j).
  13.     int[][] minCost = new int[helper.length][helper.length];
  14.     for (int i = 1; i < helper.length; i++) {
  15.       for (int j = i - 1; j >= 0; j--) {
  16.         if (j + 1 == i) {
  17.           minCost[j][i] = 0;
  18.         } else {
  19.           minCost[j][i] = Integer.MAX_VALUE;
  20.           for (int k = j + 1; k <= i - 1; k++) {
  21.             minCost[j][i] = Math.min(minCost[j][i], minCost[j][k] + minCost[k][i]);
  22.           }
  23.           minCost[j][i] += helper[i] - helper[j];
  24.         }
  25.       }
  26.     }
  27.     return minCost[0][helper.length - 1];
  28.   }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement