Advertisement
bkit4s0

[cut-rod]

May 10th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 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 + 1];
  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.         /**
  24.          * use r with lenght n or length n+1
  25.          */
  26.         if (r[n] > 0)
  27.             return r[n];
  28.         int q;
  29.         if (n == 0)
  30.             q = 0;
  31.         else {
  32.             q = -1;
  33.             for (int i = 1; i <= n; i++)
  34.                 q = Math.max(q, p[i] + memoized_cut_rod_aux(p, n - i, r));
  35.         }
  36.         r[n] = q;
  37.         return q;
  38.     }
  39.  
  40.     private static int bottom_up_cut_rod(int p[], int n) {
  41.         int[] r = new int[n + 1];
  42.         r[0] = 0;
  43.         for (int j = 1; j <= n; j++) {
  44.             int q = -1;
  45.             for (int i = 1; i <= j; i++)
  46.                 q = Math.max(q, p[i] + r[j - i]);
  47.             r[j] = q;
  48.         }
  49.         return r[n];
  50.     }
  51.  
  52.     public static void main(String args[]) throws NumberFormatException,
  53.             IOException {
  54.         int[] p = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
  55.         int r = 4;
  56.         int result;
  57.         // result = cut_rod(p,r);
  58.         // result = memoized_cut_rod(p, r);
  59.         result = bottom_up_cut_rod(p, r);
  60.         System.out.println(result);
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement