pkbagchi

Fractional knapsack

Mar 26th, 2019
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. # include<stdio.h>
  2.  
  3. void knapsack(int n, float weight[], float profit[], float capacity) {
  4.    float x[20], tp = 0;
  5.    int i, j, u;
  6.    u = capacity;
  7.  
  8.    for (i = 0; i < n; i++){
  9.       x[i] = 0.0;
  10.    }
  11.  
  12.    for (i = 0; i < n; i++) {
  13.       if (weight[i] > u)
  14.          break;
  15.       else {
  16.          x[i] = 1.0;
  17.          tp = tp + profit[i];
  18.          u = u - weight[i];
  19.       }
  20.    }
  21.  
  22.   // if (i < n)
  23.       x[i] = u / weight[i];
  24.  
  25.    tp = tp + (x[i] * profit[i]);
  26.  
  27.    printf("\nThe result vector is:- ");
  28.    for (i = 0; i < n; i++)
  29.       printf("%f\t", x[i]);
  30.  
  31.    printf("\nMaximum profit is:- %f", tp);
  32.  
  33. }
  34.  
  35. int main() {
  36.    float weight[20], profit[20], capacity;
  37.    int num, i, j;
  38.    float ratio[20], temp;
  39.  
  40.    printf("\nEnter the no. of objects:- ");
  41.    scanf("%d", &num);
  42.  
  43.    printf("\nEnter the wts and profits of each object:- ");
  44.    for (i = 0; i < num; i++) {
  45.       scanf("%f %f", &weight[i], &profit[i]);
  46.    }
  47.  
  48.    printf("\nEnter the capacityacity of knapsack:- ");
  49.    scanf("%f", &capacity);
  50.  
  51.    for (i = 0; i < num; i++) {
  52.       ratio[i] = profit[i] / weight[i];
  53.    }
  54.  
  55.    for (i = 0; i < num; i++) {
  56.       for (j = i + 1; j < num; j++) {
  57.          if (ratio[i] < ratio[j]) {
  58.             temp = ratio[j];
  59.             ratio[j] = ratio[i];
  60.             ratio[i] = temp;
  61.  
  62.             temp = weight[j];
  63.             weight[j] = weight[i];
  64.             weight[i] = temp;
  65.  
  66.             temp = profit[j];
  67.             profit[j] = profit[i];
  68.             profit[i] = temp;
  69.          }
  70.       }
  71.    }
  72.  
  73.    knapsack(num, weight, profit, capacity);
  74.    return(0);
  75. }
Advertisement
Add Comment
Please, Sign In to add comment