hdu 2546 饭卡 01背包

本文介绍了一个01背包问题的小变种,通过先选取最大价值物品再使用01背包算法解决剩余部分的方法,特别指出若初始金额小于5则直接输出。提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2546

 

一个01背包的小小变式

 

先贪心取一个最大值

然后剩下的用01背包做

最后减掉那个最大值

 

可能的坑点在于如果给出的钱数本身就小于5则需要直接输出

 

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <stack>
#include <set>
#include <queue>
#include <vector>

using namespace std;

typedef long long ll;

const int maxn = 1010;

int w[maxn], c[maxn], f[maxn];
int ans;
int n, V;


void ZeroOnePack(int cost, int weight)
{
    for(int i = V; i >= cost; i--)
    {
        f[i] = max(f[i], f[i-cost] + weight);
        if(f[i] > ans)
            ans = f[i];
    }
}

int main()
{
    //freopen("in.txt", "r", stdin);

    while(scanf("%d", &n) == 1 && n != 0)
    {
        ans = 0;
        memset(f, 0, sizeof(f));

        int maxnum = 0;
        for(int i = 0; i < n; i++)
        {
            scanf("%d", &w[i]);
            if(w[i] > maxnum)
                maxnum = w[i];
        }

        scanf("%d", &V);

        if(V < 5)
        {
            printf("%d\n", V);
            continue;
        }


        V -= 5;

        bool flag = true;
        for(int i = 0; i < n; i++)
        {
            if(flag && w[i] == maxnum)
            {
                flag = false;
                continue;
            }
            ZeroOnePack(w[i], w[i]);
        }

        printf("%d\n", (V - ans) - maxnum + 5);
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/dishu/p/4295563.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值