Problem Description
Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave …
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?
Input
The first line contain a integer T , the number of
cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.
Output
One integer per line representing the maximum of the
total value (this number will be less than 231).
Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14
解题心得:
这是一个背包问题,但是还没学会动态规划的方法,只好用贪心法求解,但提交一直是wronganswer,谁看到了请告诉我。
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; typedef struct{ int val; int vol; float vv; }Bone; bool compare(Bone a,Bone b) { if(a.vv==b.vv){ return a.vol>b.vol; } return a.vv>b.vv; } int main() { int t;//t组测试数据 int n;//n个骨头 int v;//书包能装的体积 int now_v=0;//已装入的体积 int j1=0;//已装入的个数 int sum=0;//已装入的总价值 Bone bone[1005]; cin>>t; for(int i=0;i<t;i++){ scanf("%d %d",&n,&v); for(int j=0;j<n;j++){ scanf("%d",&bone[j].val); } for(int j=0;j<n;j++){ scanf("%d",&bone[j].vol); } for(int j=0;j<n;j++){ bone[j].vv=(float)bone[j].val/(float)bone[j].vol; } sort(bone,bone+n,compare); //for(int j=0;j<n;j++){ // cout<<bone[j].vv<<" "; // cout<<bone[j].val<<" "<<endl; //} for(int j=0;j<n;j++){ now_v+=bone[j].vol;//循环一次往里装一次 j1++; if(now_v>=v){ break; } } if(now_v==v){ for(int j=0;j<j1;j++){ sum+=bone[j].val; } } if(now_v>v){ for(int j=0;j<j1-1;j++){ sum+=bone[j].val; } } if(now_v<v){ for(int j=0;j<n;j++){ sum+=bone[j].val; } } cout<<sum<<endl; now_v=0; sum=0; j1=0; } return 0; }