fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Item struct
  5. typedef struct { int v, w; float r; } Item;
  6.  
  7. // Compare function for qsort (descending ratio)
  8. int compare(const void *a, const void *b) {
  9. float rA = ((Item *)a)->r;
  10. float rB = ((Item *)b)->r;
  11. if (rA < rB) return 1;
  12. if (rA > rB) return -1;
  13. return 0;
  14. }
  15.  
  16. // Greedy Rational Knapsack solution
  17. float knapsack(float capacity, Item items[], int n) {
  18. float totalValue = 0.0;
  19. int i;
  20.  
  21. for (i = 0; i < n; i++) {
  22. items[i].r = (float)items[i].v / items[i].w;
  23. }
  24. qsort(items, n, sizeof(Item), compare);
  25.  
  26. for (i = 0; i < n; i++) {
  27. if (capacity <= 0) break;
  28.  
  29. if (items[i].w <= capacity) {
  30. totalValue += items[i].v;
  31. capacity -= items[i].w;
  32. } else {
  33. totalValue += items[i].v * (capacity / items[i].w);
  34. capacity = 0;
  35. }
  36. }
  37. return totalValue;
  38. }
  39.  
  40. // Main function for testing
  41. int main() {
  42. float W = 50.0;
  43. Item goods[] = {{60, 10, 0}, {100, 20, 0}, {120, 30, 0}};
  44. int N = 3;
  45.  
  46. float result = knapsack(W, goods, N);
  47.  
  48. printf("Nilai Optimal Knapsack (W=%.0f): %.2f\n", W, result); // Output: 240.00
  49. return 0;
  50. }
Success #stdin #stdout 0s 5324KB
stdin
5
5 4 7 8 10
10 5 7 12 8
20
stdout
Nilai Optimal Knapsack (W=50): 240.00