Advertisement
Guest User

nunu

a guest
Dec 22nd, 2014
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. double p[100],w[100],ppw[100],x[100],profit=0.0;
  4.  
  5. void sort(int n);
  6. void greedy_knapsack(int m,int n);
  7.  
  8. int main()
  9. {
  10.     int i,j,n,capacity;
  11.  
  12.     printf("What is the capacity of your knapsack: ");
  13.     scanf("%d",&capacity);
  14.  
  15.     printf("How many items are there to steal: ");
  16.     scanf("%d",&n);
  17.  
  18.     printf("Enter the Price and Weight of the items: ");
  19.  
  20.     for(i=0;i<n;i++)
  21.     {
  22.         scanf("%lf %lf",&p[i],&w[i]);
  23.         ppw[i]=p[i]/w[i];
  24.     }
  25.  
  26.     sort(n);
  27.     greedy_knapsack(capacity,n);
  28.  
  29.     printf("Total profit is: ");
  30.     for(i=0;i<n;i++)
  31.     {
  32.         profit=profit+(x[i]*p[i]);
  33.     }
  34.  
  35.     printf("%lf",profit);
  36.  
  37.     return 0;
  38. }
  39.  
  40. void sort(int n)
  41. {
  42.     int i,j;
  43.     double temp1,temp2,temp3;
  44.  
  45.     for(i=1;i<=n;i++)
  46.     {
  47.         temp1=ppw[i];
  48.         temp2=p[i];
  49.         temp3=w[i];
  50.         j=i-1;
  51.  
  52.         while (j>=0 && ppw[j]<temp1)
  53.         {
  54.             ppw[j+1]=ppw [j];
  55.             p[j+1]=p[j];
  56.             w[j+1]=w[j];
  57.             j--;
  58.         }
  59.  
  60.         ppw[j+1]=temp1;
  61.         p[j+1]=temp2;
  62.         w[j+1]=temp3;
  63.     }
  64. }
  65.  
  66. void greedy_knapsack(int m,int n)
  67. {
  68.     int i;
  69.     double u;
  70.  
  71.     for(i=1;i<=n;i++)
  72.         x[i]=0.0;
  73.     u=m;
  74.  
  75.     for(i=1;i<=n;i++)
  76.     {
  77.         if(w[i]>u)
  78.             break;
  79.         x[i]=1.0;
  80.         u=u-w[i];
  81.     }
  82.  
  83.     if(i<=n)
  84.         x[i]=u/w[i];
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement