Advertisement
bkit4s0

[cut-rod] top-down with memoization implements

May 10th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. import java.io.IOException;
  2.  
  3. class type {
  4.  
  5.     static int cut_rod(int p[], int n) {
  6.         if (n == 0)
  7.             return 0;
  8.         int q = -1;
  9.         for (int i = 1; i <= n; i++)
  10.             q = Math.max(q, p[i] + cut_rod(p, n - i));
  11.         return q;
  12.     }
  13.  
  14.     static int memoized_cut_rod(int p[], int n) {
  15.         int[] r = new int[n];
  16.         for (int i = 0; i < n; i++) {
  17.             r[i] = -1;
  18.         }
  19.         return memoized_cut_rod_aux(p, n, r);
  20.     }
  21.  
  22.     private static int memoized_cut_rod_aux(int[] p, int n, int[] r) {
  23.         if (r[n] > 0)
  24.             return r[n];
  25.         int q;
  26.         if (n == 0)
  27.             q = 0;
  28.         else {
  29.             q = -1;
  30.             for (int i = 0; i < n; i++)
  31.                 q = Math.max(q, p[i] + memoized_cut_rod_aux(p, n - i, r));
  32.         }
  33.         r[n] = q;
  34.         return q;
  35.     }
  36.  
  37.     public static void main(String args[]) throws NumberFormatException,
  38.             IOException {
  39.         int[] p = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
  40.         int r = 4;
  41.         int result;
  42.         // result = cut_rod(p,r);
  43.         result = memoized_cut_rod(p, r);
  44.         System.out.println(result);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement