Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- float w[100],p[100],x[100];
- int n;
- class ksack
- {
- public:
- void knapsack(int m,int n)
- {
- for(int i=1;i<n;i++)
- {
- int max=i;
- for(int j=i+1;j<=n;j++)
- {
- if((p[j]/w[j])>(p[max]/w[max]))
- {
- max=j;
- }
- }
- swap(p[max],p[i]);
- swap(w[max],w[i]);
- }
- int u=m;
- int i;
- for(i=1;i<=n;i++)
- {
- if(w[i]>u) break;
- x[i]=1;
- u=u-w[i];
- }
- if(i<=n)
- {
- x[i]=u/w[i];
- }
- }
- void profit(int n)
- {
- float sum=0;
- for(int i=1;i<=n;i++)
- sum+=w[i]*x[i]*p[i];
- cout<<endl<<"total profit:"<<sum;
- }
- };
- int main()
- {
- ksack k;
- //int n;
- freopen("in.txt","r",stdin);
- //cout<<"Enter the number of item :";
- cin>>n;
- //cout<<"Enter the number of profits:";
- for(int i=1;i<=n;i++)
- {
- cin>>p[i]>>w[i];
- }
- cout<<"number of item:"<<n<<endl;
- cout<<"number of profits:";
- for(int i=1;i<=n;i++)
- {
- cout<<p[i]<<" ";
- }
- cout<<endl<<"number of weight:";
- for(int i=1;i<=n;i++)
- {
- cout<<w[i]<<" ";
- }
- k.knapsack(60,n);
- cout<<endl<<"number of profits swap:";
- for(int i=1;i<=n;i++)
- {
- cout<<p[i]<<" ";
- }
- cout<<endl<<"number of weight swap:";
- for(int i=1;i<=n;i++)
- {
- cout<<w[i]<<" ";
- }
- cout<<endl<<"number of portion:";
- for(int i=1;i<=n;i++)
- {
- cout<<x[i]<<" ";
- }
- k.profit(n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement