jakaria_hossain

0-1 knapsack

Oct 23rd, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. #include<stdio.h>
  2. typedef struct
  3. {
  4. int item;
  5. int value;
  6. int weight;
  7. }knap_sack;
  8. int main()
  9. {
  10. knap_sack knapsack[100];
  11. int n,i,j,array[100],k=0,maxweight,maxVal=0;
  12. printf("How many item do you have?\n");
  13. scanf("%d",&n);
  14. printf("Enter item number, its value and weight\n");
  15. for(i=0;i<n;i++)scanf("%d %d %d",&knapsack[i].item,&knapsack[i].value,&knapsack[i].weight);
  16. printf("Enter maximum weight\n");
  17. scanf("%d",&maxweight);
  18. int table[n+1][maxweight+1];
  19. for(i=0;i<=n;i++)
  20. {
  21. for(j=0;j<=maxweight;j++)
  22. {
  23. if(i==0 || j==0)table[i][j]=0;
  24. else if(j-knapsack[i-1].weight<0)table[i][j]=table[i-1][j];
  25. else
  26. {
  27. if(table[i-1][j-knapsack[i-1].weight]+knapsack[i-1].value>table[i-1][j])
  28. table[i][j]=table[i-1][j-knapsack[i-1].weight]+knapsack[i-1].value;
  29. else table[i][j]=table[i-1][j];
  30. }
  31. }
  32. }
  33. i=n,j=maxweight;
  34. while(i>=0 && j>=0)
  35. {
  36. if(table[i][j]==0)break;
  37. else
  38. {
  39. if(table[i-1][j]<table[i][j])
  40. {
  41. maxVal=knapsack[i-1].value+maxVal;
  42. array[k++]=knapsack[i-1].item;
  43. j=j-knapsack[i-1].weight;
  44. i=i-1;
  45. }
  46. else i=i-1;
  47. }
  48. }
  49. printf("\nMaximum price is %d \n",maxVal);
  50. printf("Items are\n");
  51. for(i=k-1;i>=0;i--)printf("%d ",array[i]);
  52. return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment