Bone Collector
题目链接
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
题目翻译
骨头收集者
给t组数据,每组数据给出 骨头数量,和背包容量,然后输入骨头价值,下面一行对应着骨头的体积;
问能收集的骨头价值最大.
题目分析
背包01问题就是一个东西选与不选,选只能选一次.
背包01问题的模板,这是简单的二维,还可以压缩为一维减少空间使用(现在还不咋清楚就先不写了);
给一个比较清楚的c++解法可以参考一下一维;
c++
for (int i = 1; i <= a; i++) {
for (int j = 0; j <= b; j++) {
bb[i][j] = bb[i - 1][j];
if (j >= tj[i]) {
bb[i][j] = Math.max(bb[i - 1][j], bb[i - 1][j - tj[i]] + jz[i]);
}
}
}
代码实现
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int bb[][] = new int[1005][1005];//背包
int jz[] = new int[1005];//价值
int tj[] = new int[1005];//体积
int n, a, b;
in.nextToken();
n = (int) in.nval;
for (int s = 0; s < n; s++) {
in.nextToken();
a = (int) in.nval;
in.nextToken();
b = (int) in.nval;
for (int i = 1; i <= a; i++) {
in.nextToken();
jz[i] = (int) in.nval;
}
for (int i = 1; i <= a; i++) {
in.nextToken();
tj[i] = (int) in.nval;
}
for (int i = 1; i <= a; i++) {
for (int j = 0; j <= b; j++) {//遍历背包的体积
bb[i][j] = bb[i - 1][j];//背包继承
if (j >= tj[i]) {//如果现在的体积还够用
bb[i][j] = Math.max(bb[i - 1][j], bb[i - 1][j - tj[i]] + jz[i]);
//比较当前价值与背包空间减去当前骨头的体积再加上当前骨头的价值;
}
}
}
out.println(bb[a][b]);//最后的背包一定是价值最高的
out.flush();
}
}
}