HDU - 2546 饭卡 【01背包+排序】

题目链接: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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值