//程序写得有些长,请原谅啊.若有更为简洁的程序,请不吝赐教!有些显得罗嗦的语句只是输出格式而已#include<iostream>
#include<cstring>
#define N 3
using namespace std;
void swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
};
int pwi[N];
void Sortarr(float pw[],int n,int pwi[])
{
int i,j;
int temp[N];
for(i=0;i<N;i++)temp[i]=0;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(pw[i]>pw[j])temp[j]=temp[j]+1;//越小的数,里面的数字越大
else temp[i]=temp[i]+1;
}cout<<"temp[i] 的值为:"<<endl;
for(i=0;i<n;i++)cout<<temp[i]<<" ";
cout<<endl;
//让pwi[]记下原来从小到大的坐标
int s[N];
for(i=0;i<n;i++)
s[temp[i]]=pwi[i];
for(i=0;i<n;i++)
pwi[i]=s[i];
cout<<"排序后pwi[]的情况为"<<endl;
for(i=0;i<n;i++)cout<<pwi[i]<<" ";
cout<<endl;
}
int Knapsackgready(int W[],int p[],int n,int M,float x[])
{void Sortarr(float pw[],int n,int pwi[]);
int remains;
float pw[N];
int i;
for(i=0;i<n;i++)pw[i]=p[i]/float(W[i]);
cout<<"pw[i] de zhi:"<<endl;
for(i=0;i<n;i++)cout<<pw[i]<<" ";
cout<<endl;
Sortarr(pw,n,pwi);
int k;
for(i=0;i<n;i++)x[i]=0;
remains=M;
i=0;
k=pwi[i];
while(W[k]<=remains)
{
x[k]=1;
remains=remains-W[k];
i++;
k=pwi[i];
}
x[k]=remains/float(W[k]);
return i;
};
void main()
{int Knapsackgready(int W[] ,int p[] ,int n ,int M,float x[]);
int W[N]={40,15,24};
int P[N]={35,25,24};
float x[N];
int M=40;
int n=N;
int k,i;
for(i=0;i<N;i++)pwi[i]=i;
cout<<"pwi[i] 的初始值为:"<<endl;
for( i=0;i<n;i++)cout<<pwi[i]<<" ";
cout<<endl;
k=Knapsackgready(W,P,n,M,x);
float LR=0;
cout<<"k="<<k<<endl;
for(i=0;i<=k;i++){LR=x[pwi[i]]*P[pwi[i]]+LR;}
cout<<"装的总价值为:"<<LR<<endl;
for(i=0;i<=k;i++) cout<<"装的物品p["<<i<<"]为"<<x[i]<<" "<<"重量为"<<x[pwi[i]]*W[pwi[i]]<<endl;
}