HDU 2602 0-1 背包问题,题目的链接如下:
http://acm.hdu.edu.cn/showproblem.php?pid=2602
A - hdu 2602
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit
Status
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
Hint
By AC_gsws
这题的大致题意就是:你要用V体积的背包装最大价值的东西。本题有两种方法,第一种的空间复杂度为O(NV),第二种的空间复杂度为O(V);
没有优化的代码
//这题的状态就是只算前i件物品,容量为v的时候最大价值
//状态转移方程就是f[i][v] = max(f[i-1][v], f[i-1][v-c[i][1]] + c[i][0]);
//其中f[i-1][v] 就是不选这个物品的最大价值,c[i][1] 就是选择这件物品后的最大价值,两个一比较返回大的那个就是当前的最大价值。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int c[1001][2];
int f[1001][1001];
int main()
{
int t, n, m;
cin >> t;
while(t--){
cin >> n >> m;
for(int i = 1 ; i <= n ; i++)
cin >> c[i][0];//物品的价值;
for(int i = 1 ; i <= n ; i++)
cin >> c[i][1];//物体的体积
for(int i = 0 ; i <= n ; i++)
f[0][i] = 0;//先对第一层置零;
for(int i = 1 ; i <= n ; i++)
for(int v = 0 ; v <= m ; v++)
if(v >= c[i][1]){
f[i][v] = max(f[i-1][v], f[i-1][v-c[i][1]] + c[i][0]);
}
else if(v < c[i][1]) f[i][v] = f[i-1][v];
cout << f[n][m] << endl;
}
return 0;
}
下面是优化过的版本:
//优化的思想就是先把数组f置零,然后每一次都从f[m] 开始循环,
//因为,从前面的话,他就会把上一个状态的f[i-1] 覆盖,
//下一个f[i]用f[i-1]的时候就找不到上一个状态的f[i]了,
//然后从后面的话,我们就能每一次用f[i-1]的时保证他是上一个状态保存的f[i]
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int c[1005][2];
int f[1005];
int main()
{
int t, n, m;
cin >> t;
while(t--){
cin >> n >> m;
for(int i = 1 ; i <= n ; i++)
cin >> c[i][0];//物品的价值;
for(int i = 1 ; i <= n ; i++)
cin >> c[i][1];//物体的体积
for(int i = 0 ; i <= m ; i++)
f[i] = 0 ;
for(int i = 1 ; i <= n ; i++)
for(int v = m ; v >= 0 ; v--){
if(v >= c[i][1])
f[v] = max(f[v], f[v-c[i][1]] + c[i][0]);
}
cout << f[m] << endl;
}
return 0;
}
很强势~~~~