#include<iostream> using namespace std; /* *背包问题不用于01背包问题 (参考我的另一篇:http://blog.csdn.net/zlb_xidian/archive/2010/07/26/5766254.aspx) * *动态规划方法能有效解决01背包问题,但其对于背包问题无法保证最终将背包装满 *故背包问题可用贪心算法简单解决 * */ template<typename T> void swap(T &a,T &b) { T temp =a; a = b; b = temp; }; template<typename T> void print_arr(T list[],int n) { cout<<"list:"; for(int i=0;i<n;i++) { cout<<list[i]<<" "; } cout<<endl; } //依据 vi/wi的大小,从大到小排序 void Sort(int n,float v[],float w[]) { int change = 0; for(int i=0;i<n-1;i++)//因为是间隔数,所以要-1 { change = 0; for(int j=0;j<n-i-1;j++) //这里仍然要-1 { if((v[j]/w[j]) < (v[j+1]/w[j+1])) { swap(v[j],v[j+1]); swap(w[j],w[j+1]); change = 1; } } if(change == 0) break; } }; void knapsack_greedy(int n,float v[],float w[],float x[],float M) { cout<<"-------before sorting---------"<<endl; print_arr(v,n); print_arr(w,n); Sort(n,v,w); cout<<"-------after sorting---------"<<endl; cout<<"value per weight:"; for(int q=0;q<n;q++) { cout<<v[q]/w[q]<<" > "; } cout<<endl; print_arr(v,n); print_arr(w,n); for(int i=0;i<n;i++) x[i] = 0; float c=M; int j; for( j=0;j<n;j++ ) { if(w[j] > c) break; x[j] = 1;//每个物品只有一个,这些如果没有装满,就补下一个 的部分 c -= w[1]; } if(j < n-1)//说明没有装满,注意n不是max值 x[j] = c/w[j];//剩下的c能装多少就装多少下一个的 cout<<"-------the best solution---------"<<endl; print_arr(x,n); }; int main() { int n; float c; cout<<"Pls input the nums and the Max:"; cin>>n>>c; float *val=new float[n];//动态一维数组 cout<<"Pls input the "<<n<<" property (val[i]):"<<endl; for(int i=0;i<n;i++) cin>>val[i]; float *wei=new float[n]; cout<<"Pls input the "<<n<<" weight (w[i]):"<<endl; for(int j=0;j<n;j++) cin>>wei[j]; //分配答案的结果 float *x=new float[n]; knapsack_greedy(n,val,wei,x,c); delete[] val,wei,x; return 1; }