Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Fractional Knapsack Problem

Knapsack (w, v, W) { Create array x[] having length n for (i=1 to n) X[i] =0 Weight = 0 i=0 while (weight < W && i<=n) { if (weight+ w[i] <=W) { x[i] = 1 weight = weight + w[i] } else { X[i] = (W-weight)/w[i] weight = W } } return x }

0/1 Knapsack Problem


Knapsack1 (k, v, W) { n= length [k] for (w=0 to W) s[0,w] = 0 for (i=1 to n) s[i,0] = 0 for (i=1 to n) { for (w=1 to W) { if (k[i]<= w) { if (v[i] + s[i-1,w-k[i]] > s[i-1, w]) s[i, w] = v[i] + s[i-1, w-k[i]] else s[i, w] = s[i-1, w] } else s[i, w] = s[i-1, w] } } return s } // k is an array which stores weights of the objects // v is an array which stores values/profit of the objects. W is the capacity of knapsack

Optimal solution set Solution (s, n, w, W) { i=n k= W Create array x [1n] initialize its elements with zero While (i>0 and k>0) { if (s[i, k] != s[i-1, k]) { x[i] = 1 k = k w[i] } i = i-1 } return x }

You might also like