Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- double p[100],w[100],ppw[100],x[100],profit=0.0;
- void sort(int n);
- void greedy_knapsack(int m,int n);
- int main()
- {
- int i,j,n,capacity;
- printf("What is the capacity of your knapsack: ");
- scanf("%d",&capacity);
- printf("How many items are there to steal: ");
- scanf("%d",&n);
- printf("Enter the Price and Weight of the items: ");
- for(i=0;i<n;i++)
- {
- scanf("%lf %lf",&p[i],&w[i]);
- ppw[i]=p[i]/w[i];
- }
- sort(n);
- greedy_knapsack(capacity,n);
- printf("Total profit is: ");
- for(i=0;i<n;i++)
- {
- profit=profit+(x[i]*p[i]);
- }
- printf("%lf",profit);
- return 0;
- }
- void sort(int n)
- {
- int i,j;
- double temp1,temp2,temp3;
- for(i=1;i<=n;i++)
- {
- temp1=ppw[i];
- temp2=p[i];
- temp3=w[i];
- j=i-1;
- while (j>=0 && ppw[j]<temp1)
- {
- ppw[j+1]=ppw [j];
- p[j+1]=p[j];
- w[j+1]=w[j];
- j--;
- }
- ppw[j+1]=temp1;
- p[j+1]=temp2;
- w[j+1]=temp3;
- }
- }
- void greedy_knapsack(int m,int n)
- {
- int i;
- double u;
- for(i=1;i<=n;i++)
- x[i]=0.0;
- u=m;
- for(i=1;i<=n;i++)
- {
- if(w[i]>u)
- break;
- x[i]=1.0;
- u=u-w[i];
- }
- if(i<=n)
- x[i]=u/w[i];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement