Vikhyath_11

p6

Jul 26th, 2024
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int max(int a, int b) {
  4. return (a > b) ? a : b;
  5. }
  6.  
  7. int main() {
  8. int n, m;
  9.  
  10. // Read the number of items
  11. printf("Enter the number of items: ");
  12. scanf("%d", &n);
  13.  
  14. // Arrays to store profits and weights
  15. int P[n + 1], wt[n + 1];
  16.  
  17. // Read the profits and weights
  18. printf("Enter the profits of the items:\n");
  19. for (int i = 1; i <= n; i++) {
  20. printf("Profit of item %d: ", i);
  21. scanf("%d", &P[i]);
  22. }
  23.  
  24. printf("Enter the weights of the items:\n");
  25. for (int i = 1; i <= n; i++) {
  26. printf("Weight of item %d: ", i);
  27. scanf("%d", &wt[i]);
  28. }
  29.  
  30. // Read the maximum weight capacity
  31. printf("Enter the maximum weight capacity of the knapsack: ");
  32. scanf("%d", &m);
  33.  
  34. // DP table
  35. int K[n + 1][m + 1];
  36.  
  37. for (int i = 0; i <= n; i++) {
  38. for (int w = 0; w <= m; w++) {
  39. if (i == 0 || w == 0) {
  40. K[i][w] = 0;
  41. } else if (wt[i] <= w) {
  42. K[i][w] = max(P[i] + K[i - 1][w - wt[i]], K[i - 1][w]);
  43. } else {
  44. K[i][w] = K[i - 1][w];
  45. }
  46. }
  47. }
  48.  
  49. // Print the DP table
  50. printf("DP Table:\n");
  51. for (int i = 0; i <= n; i++) {
  52. for (int w = 0; w <= m; w++) {
  53. printf("%d\t", K[i][w]);
  54. }
  55. printf("\n");
  56. }
  57.  
  58. printf("Maximum profit is %d\n", K[n][m]);
  59.  
  60. return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment