DP–背包问题变题 Knapsack problem
原题点这里
题目
Given a set of n items, each with a weight w[i] and a value v[i], determine a way to choose the items into a knapsack so that the total weight is less than or equal to a given limit B and the total value is as large as possible. Find the maximum total value. (Note that each item can be only chosen once).
INPUT:
The first line contains the integer T indicating to the number of test cases.
For each test case, the first line contains the integers n and B.
Following n lines provide the information of each item.
The i-th line contains the weight w[i] and the value v[i] of the i-th item respectively.
1 <= number of test cases <= 100
1 <= n <= 500
1 <= B, w[i] <= 1000000000
1 <= v[1]+v[2]+…+v[n] <= 5000
All the inputs are integers.
OUTPUT:
For each test case, output the maximum value.
Sample Input
1
5 15
12 4
2 2
1 1
4 10
1 2
Sample Output
15
题目解析:
还是背包问题裸题,给定空间(或者说质量),求该空间限制下能存多少value的物品。
问题在于题目的w[i]太大了,要是用空间(质量)做dp下标的话显然不现实,所以要有一个倒转的思想:
- 原来是以空间为下标,dp该空间最大的value
- 现在是以value为下标,dp该value所需的最小空间,然后倒着遍历一遍找到一个满足空间的最大value即题目的答案了
不多说上代码与注释:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
typedef long long ll;
ll dp[5100];//记录value为下标时,占用的最小体积(重量)
int v[510];
ll w[510];
int main()
{
int t, n, B;
cin >> t;
while (t--) {
cin >> n >> B;
ll sumv = 0;
for (int i = 0; i < n; i++) {
cin >> w[i] >> v[i];
sumv += v[i];
}
memset(dp, 0x3f3f3f3f, sizeof(dp));//初始化dp数组为大值以便求最小值
dp[0] = 0;//value为0时,占用体积当然为0
for (int i = 0; i < n; i++) {
for (int j = sumv; j >= v[i]; j--) {
ll temp = dp[j - v[i]] + w[i];//将当前value减去v[i],腾出空间给第i包,此时占用的空间为temp;
if (temp <= B && temp < dp[j])//此次尝试若符合B的限制且比原有计划更加省空间(重量),则采取新方案;
dp[j] = temp;
}
}
for (int j = sumv; j >= 0; j--) {
if (dp[j] <= B) {//找到B限制下最大的占空间,此时对应的value也最高
cout << j << endl;
break;
}
}
}
return 0;
}