fork download
  1. #include<stdio.h>
  2. void fractional_knapsack(float weight[],float profit[],int n,int capacity)
  3. {
  4. int i;
  5. int used[100];
  6. for(i=0;i<n;i++)
  7. {
  8. used[i]=0;
  9. }
  10. float total_profit =0.0;
  11. int remaining_capacity = capacity;
  12. float X[n];
  13. while(remaining_capacity>0)
  14. {
  15. int best_index=-1;
  16. float best_ratio=0.0;
  17. for(i=0;i<n;i++)
  18. {
  19. if(used[i]==0)
  20. {
  21. float ratio =profit[i]/weight[i];
  22. if(ratio>best_ratio)
  23. {
  24. best_ratio=ratio;
  25. best_index=i;
  26. }
  27. }
  28. }
  29. if (best_index==-1)
  30. {
  31. break;
  32. }
  33. used[best_index]=1;
  34. if(weight[best_index]<=remaining_capacity)
  35. {
  36. X[best_index]=1;
  37. total_profit+=profit[best_index];
  38. remaining_capacity-=weight[best_index];
  39. }
  40. else
  41. {
  42. X[best_index]=(remaining_capacity/weight[best_index]);
  43. total_profit+=profit[best_index]*(remaining_capacity/weight[best_index]);
  44. remaining_capacity=0;
  45. }
  46. }
  47. printf("X[]:");
  48. for(i=0;i<n;i++)
  49. {
  50. printf(" %.2f ",X[i]);
  51. }
  52. printf("\ntotal profit is :%.2f",total_profit);
  53. }
  54. int main()
  55. {
  56. int n;
  57. int i;
  58. float weight[n];
  59. float profit[n];
  60. int capacity;
  61. printf("enter items :");
  62. scanf("%d",&n);
  63. printf("enter capacity :");
  64. scanf("%f",&capacity);
  65. printf("enter weights");
  66. for(i=0;i<n;i++)
  67. {
  68. scanf("%f",&weight[i]);
  69. }
  70. printf("enter profits :");
  71. for(i=0;i<n;i++)
  72. {
  73. scanf("%f",&profit[i]);
  74. }
  75. fractional_knapsack(weight,profit,n,capacity);
  76. return 0;
  77. }
Success #stdin #stdout 0.01s 5316KB
stdin
45
stdout
enter items :enter capacity :enter weightsenter profits :X[]: -0.00  0.00  -0.00  0.00  -0.00  0.00  -0.00  0.00  0.00  0.00  -0.00  0.00  -0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00  -0.00  0.00  0.00  0.00  -nan  -nan  -0.00  0.00  -0.00  0.00  -0.00  0.00  -0.00  0.00  0.00 
total profit is :0.00