Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- class Knapsack
- {
- static double max(double a, double b) { return (a > b)? a : b; }
- // Returns the maximum value that can be put in a knapsack of capacity W
- static ArrayList<Double> knapSack(double W, double wt[])
- {
- W*= 100;
- int n = wt.length;
- for (int i = 0; i < wt.length; i++)
- {
- wt[i] *= 100;
- }
- int K[][] = new int[n+1][(int)W+1];
- // Build table K[][] in bottom up manner
- for (int i = 0; i <= n; i++)
- {
- for (int w = 0; w <= W; w++)
- {
- if (i==0 || w==0)
- K[i][w] = 0;
- else if (wt[i-1] <= w)
- K[i][w] = (int) max(wt[i-1] + K[i-1][(int) (w-wt[i-1])], K[i-1][w]);
- else
- K[i][w] = K[i-1][w];
- }
- }
- return output(K,n,(int)W,wt);
- }
- private static ArrayList<Double> output(int[][] K, int n, int W, double[] wt)
- {
- ArrayList<Double> out = new ArrayList<Double>();
- int res = K[n][W];
- int w = W;
- for (int i = n; i > 0 && res > 0; i--) {
- // either the result comes from the top
- // (K[i-1][w]) or from (val[i-1] + K[i-1]
- // [w-wt[i-1]]) as in Knapsack table. If
- // it comes from the latter one/ it means
- // the item is included.
- if (res == K[i - 1][w])
- continue;
- else {
- // This item is included.
- out.add(wt[i - 1]/100);
- // Since this weight is included its
- // value is deducted
- res = (int) (res - wt[i - 1]);
- w = (int) (w - wt[i - 1]);
- }
- }
- return out;
- }
- public static void main(String args[])
- {
- //[2.5, 4.0, 11.5, 7.0, 15.0, 4.0, 6.0, 8.0]
- double wt[] = new double[]{2.5, 4.0, 11.5, 7.0, 15.0, 4.0, 6.0, 8.0};
- double W = 6.5;
- int n = wt.length;
- System.out.println(knapSack(W, wt));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement