Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- double profit[10000],weight[1000],w_taken[10000];
- int n,u;
- class knapsack{
- public:
- void input()
- {
- cin>>n>>u;
- for(int i=0; i<n; i++)
- {
- cin>>profit[i]>>weight[i];
- }
- }
- void solution()
- {
- selection_sort();
- int i;
- for( i =0 ;i<n; i++)
- {
- if(weight[i] > u)
- break;
- w_taken[i] = 1;
- u-=weight[i];
- }
- if(u!=0 && i<n)
- {
- w_taken[i] = u/weight[i];
- }
- profit_calculation();
- }
- void profit_calculation()
- {
- double sum = 0;
- for(int i=0; i<n; i++)
- {
- sum += w_taken[i]*profit[i];
- }
- cout<<sum;
- }
- void selection_sort()
- {
- for(int i =0; i<n-1; i++)
- {
- int max_index = i;
- for(int j = i+1; j<n; j++)
- {
- if( profit[j]/weight[j] > profit[max_index]/weight[max_index])
- max_index = j;
- }
- swap(profit[max_index],profit[i]);
- swap(weight[max_index],weight[i]);
- }
- }
- };
- int main()
- {
- freopen("input.txt","r",stdin);
- knapsack fk;
- fk.input();
- fk.solution();
- }
- /*
- input:
- 4 70
- 30 10
- 280 40
- 180 20
- 80 10
- ans 540
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement