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 ?
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.
Output
One integer per line representing the maximum of the total value (this number will be less than 2 31).
Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14
思路:
状态转移方程:val[j]=max{val[j],val[j-weight[i]]+p[i]}
val[j]表示:前i个物体在容量为vol最大的装载量
源代码:
1 #include<iostream> 2 #include<algorithm> 3 #include<string> 4 #include<cstring> 5 #include<cmath> 6 using namespace std; 7 #define maxn 1000+10 8 int val[maxn], weight[maxn], p[maxn]; 9 int main() 10 { 11 int T; 12 cin >> T; 13 while (T--) 14 { 15 int n, vol; 16 cin >> n >> vol; 17 for (int i = 1; i <= n; i++) 18 { 19 cin >> p[i]; 20 } 21 for (int j = 1; j <= n; j++) 22 { 23 cin >> weight[j]; 24 } 25 for (int j = 0; j <= vol; j++) 26 { 27 val[j] = 0; 28 } 29 for (int i = 1; i <= n; i++) 30 { 31 for (int j = vol; j >= weight[i]; j--) 32 { 33 val[j] = max(val[j], val[j - weight[i]] + p[i]); 34 35 } 36 } 37 cout << val[vol] << endl; 38 39 } 40 return 0; 41 42 }
心得:
背包入门~~~~理解一个方程还是挺费劲的,/(ㄒoㄒ)/~~不过终于比之前好多了。。。。给自己一个赞!不过还是觉得好神奇
(*^__^*) 嘻嘻……