#include <iostream>
using namespace std;
int w[10],p[10],p_no[10],n,m;
float pwr[10];
template <class T>
void swap(T *a,int i,int j){
T temp;
temp=a[j];
a[j]=a[i];
a[i]=temp;
return;}
void display(){
cout<<"\nBanyak Produk :\t"<<n<<"\nK:\t"<<m<<"\n";
cout<<"\nNo\t\tBerat\t\tProfit\t\tDensity(P/w)\n";
for(int i=0;i<n;i++)
cout<<p_no[i]<<"\t\t"<<w[i]<<"\t\t"<<p[i]<<"\t\t"<<pwr[i]<<"\n";
}
void knapsack(){
int u,i;
u=m;
float x[10];
for(i=0;i<n;i++)
x[i]=0;
for(i=0;i<n;i++){
if(w[i]>u)
break;
else{
x[i]=1;
u=u-w[i];}
}
if(i<=n)
x[i]=(float)u/w[i];
for(i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(p_no[i]>p_no[j]) {
swap(p_no,i,j);
swap(x,i,j);
swap(p,i,j);
}
}
}
float pemecahan_masalah=0;
cout<<"\nBarang Yang dibawa : \n\n";
cout<<"(";
for(i=0;i<n;i++)
cout<<p_no[i]<<" ";
cout<<")";
cout<<"\t\t(";
for(i=0;i<n;i++)
{
cout<<x[i]<<" ";
pemecahan_masalah=pemecahan_masalah+(p[i]*x[i]);
}
cout<<")";
cout<<"\n\nSolusi Optimal : \t"<<pemecahan_masalah;
}
int main(int argc, char *argv[]){
int i;
cout<<"\nK : ";
cin>>m;
cout<<"Jumlah Banyaknya : ";
cin>>n;
for(i=0;i<n;i++)
{
p_no[i]=i+1;
cout<<"\nBarang "<<i+1<<"\nW:\t";
cin>>w[i];
cout<<"P:\t";
cin>>p[i];
pwr[i]=(float)p[i]/w[i];
}
display();
for(i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(pwr[i]<pwr[j])
{
swap(p_no,i,j);
swap(w,i,j);
swap(p,i,j);
swap(pwr,i,j);
}
}
}
display();
knapsack();
cout<<"\n\n";
return 0;
}