版权声明:如需转载,记得标识出处 https://blog.csdn.net/godleaf/article/details/88713602
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2546
题目问的是最小容量,而且容量可能会负数,我们可以换个角度解决问题,比如题目允许的容量是 5~m,我们可以把容量设置成
m~2*m-5,这样做的好处是能把可能为负数的结果变成正数,那么就可以用01背包求解问题(dp[容量]),求的是最大值。
另外需要给价格排序,比如下面这个两个数据,自己可以在没排序的情况下对比一下
2 1 11 6
2 11 1 6
两个样例只是价格的顺序不同,数据不是很复杂,自己在纸上演算一下就知道为什么要排序了。(贪心的思想)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int Maxn = 1010;
const int INF = 0x3f3f3f3f;
const int LINF = 1e18;
int dp[Maxn<<2], a[Maxn];
int main(void)
{
int n;
while(scanf("%d", &n) != EOF) {
if(!n) break;
memset(dp, 0, sizeof(dp));
for(int i = 0; i < n; ++i) scanf("%d", &a[i]);
int k, limt, maxn;
scanf("%d", &k);
if(k < 5) {
cout << k << endl; continue;
}
sort(a, a+n);
limt = k+(k-5);
dp[k] = 1; maxn = k;
for(int i = 0; i < n; ++i) {
for(int j = (Maxn<<2)-1; j >= k+a[i]; --j) {
if(dp[j-a[i]] == 1 && j-a[i] <= limt) {
dp[j] = 1; maxn = max(maxn, j);
}
}
}
maxn = 2*k-maxn;
cout << maxn << endl;
}
return 0;
}