Loading…
DAA · Dynamic programming · Program 13 · In the record
Write a program in c to solve the 0/1 knapsack problem using dynamic programming and find its execution time using the time function.
Algorithm: Knapsack01(v, wt, n, W) 1. Start 2. For w <- 0 to W do 3. V[0][w] <- 0 4. For i <- 1 to n do 5. For w <- 0 to W do 6. if wt[i] <= w and v[i] + V[i-1][w-wt[i]] > V[i-1][w] then 7. V[i][w] <- v[i] + V[i-1][w-wt[i]] 8. keep[i][w] <- 1 9. else 10. V[i][w] <- V[i-1][w] 11. keep[i][w] <- 0 12. print "Maximum value" V[n][W] 13. w <- W 14. For i <- n down to 1 do 15. if keep[i][w] == 1 then 16. print "Item i selected" 17. w <- w - wt[i] 18. Stop
1#include<stdio.h>2#include<time.h>3 4int main() {5 int n,W,i,w,count=0;6 printf("Enter the number of items:");7 scanf("%d",&n);8 int v[n+1],wt[n+1];9 printf("Enter the values of %d items:",n);10 for(i=1;i<=n;i++)11 scanf("%d",&v[i]);12 printf("Enter the weights of %d items:",n);13 for(i=1;i<=n;i++)14 scanf("%d",&wt[i]);15 printf("Enter the capacity of the knapsack:");16 scanf("%d",&W);17 int V[n+1][W+1],keep[n+1][W+1];18 19 clock_t start=clock();20 for(w=0;w<=W;w++)21 V[0][w]=0;22 for(i=1;i<=n;i++) {23 for(w=0;w<=W;w++) {24 count++;25 if(wt[i]<=w && v[i]+V[i-1][w-wt[i]]>V[i-1][w]) {26 V[i][w]=v[i]+V[i-1][w-wt[i]];27 keep[i][w]=1;28 }29 else {30 V[i][w]=V[i-1][w];31 keep[i][w]=0;32 }33 }34 }35 clock_t end=clock();36 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;37 38 printf("\nV[i,w] table:\ni\\w");39 for(w=0;w<=W;w++)40 printf("\t%d",w);41 for(i=0;i<=n;i++) {42 printf("\n%d",i);43 for(w=0;w<=W;w++)44 printf("\t%d",V[i][w]);45 }46 printf("\nMaximum value:%d",V[n][W]);47 printf("\nItems selected:");48 w=W;49 for(i=n;i>=1;i--) {50 if(keep[i][w]==1) {51 printf("\tItem %d(v=%d,w=%d)",i,v[i],wt[i]);52 w=w-wt[i];53 }54 }55 printf("\nNumber of comparisons:%d",count);56 printf("\nTime taken:%f seconds",time_taken);57 printf("\nTime complexity: O(nW)");58 printf("\nSpace complexity: O(nW)");59 printf("\n");60 return 0;61}4 ⏎ 10 40 30 50 ⏎ 5 4 6 3 ⏎ 10Enter the number of items:4 Enter the values of 4 items:10 40 30 50 Enter the weights of 4 items:5 4 6 3 Enter the capacity of the knapsack:10 V[i,w] table: i\w 0 1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 10 10 10 10 10 10 2 0 0 0 0 40 40 40 40 40 50 50 3 0 0 0 0 40 40 40 40 40 50 70 4 0 0 0 50 50 50 50 90 90 90 90 Maximum value:90 Items selected: Item 4(v=50,w=3) Item 2(v=40,w=4) Number of comparisons:44 Time taken:0.000001 seconds Time complexity: O(nW) Space complexity: O(nW)
Run program 13 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.