fork download
  1. #include <stdio.h>
  2.  
  3. int w[10], p[10], n;
  4.  
  5. // Function to get max of two integers
  6. int max(int a, int b) {
  7. return a > b ? a : b;
  8. }
  9.  
  10. // Recursive knapsack function
  11. int knap(int i, int m) {
  12. if (i > n) return 0; // Base case: No more items
  13.  
  14. if (w[i] > m)
  15. return knap(i + 1, m); // Cannot include the item
  16. else
  17. return max(knap(i + 1, m), knap(i + 1, m - w[i]) + p[i]);
  18. }
  19.  
  20. int main() {
  21. int m, i, max_profit;
  22.  
  23. printf("\nEnter the number of objects: ");
  24. scanf("%d", &n);
  25.  
  26. printf("\nEnter the knapsack capacity: ");
  27. scanf("%d", &m);
  28.  
  29. printf("\nEnter profit followed by weight for each item:\n");
  30. for (i = 1; i <= n; i++) {
  31. scanf("%d %d", &p[i], &w[i]);
  32. }
  33.  
  34. max_profit = knap(1, m);
  35. printf("\nMax profit = %d\n", max_profit);
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Enter the number of objects: 
Enter the knapsack capacity: 
Enter profit followed by weight for each item:

Max profit = 0