【蓝桥备赛】明日方舟大作战——简单01背包

题目链接

明日方舟大作战

个人思路

在这里插入图片描述
需要使用有限的预算 B ,最大化我们的攻击力 attack 之和,这个就是经典的 01背包问题。
已知条件有第 i 个物品的重量 w i w_{i} wi,价值 v i v_{i} vi,以及背包的总容量 W。每个物体只有两种可能的状态(装入背包与不装入背包)。要求选若干物品放入背包使背包中物品的总价值最大且背包中物品的总重量不超过背包的容量。
在本题中,背包容量即所给预算 B,物品的重量是 干员的费用,物品的价值是 干员的攻击力。
如果在预算B的范围内,我们的攻击力之和最大只有 0 ,此时我们无法击败敌人。

参考代码

Java

import java.io.*;

public class Main {
    static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

    public static void main(String[] args) {
        Scanner sc = new Scanner();
        int n = sc.nextInt();
        int m = sc.nextInt();
        int b = sc.nextInt();
        int[][] players = new int[n][2];
        for (int i = 0; i < n; i++) {
            players[i][0] = sc.nextInt();
            players[i][1] = sc.nextInt();
        }
        int life, maxLife = 0;
        for (int i = 0; i < m; ++i) {
            life = sc.nextInt();
            if (life > maxLife) maxLife = life;
        }
        int[] f = new int[b + 1];
        // 外层先遍历干员
        for (int i = 0; i < n; ++i) {
            for (int j = b; j >= players[i][1]; --j) {
                // 当前预算不超过 j 时,使用当前干员与不使用当前干员的最大攻击力
                f[j] = Math.max(f[j], f[j - players[i][1]] + players[i][0]);
            }
        }
        if (f[b] == 0) {
            out.println(-1);
        } else
            out.println(maxLife / f[b] + (maxLife % f[b] == 0 ? 0 : 1));
        out.flush();
    }
}

class Scanner {
    static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    public int nextInt() {
        try {
            st.nextToken();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return (int) st.nval;
    }
}

C/C++

#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 3;

class Player
{
public:
    int attack, cost;
} players[N];
int n, m, b, f[N];
int life, maxLife = INT_MIN;
int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> n >> m >> b;
    for (int i = 1; i <= n; ++i)
        cin >> players[i].attack >> players[i].cost;
    for (int i = 1; i <= m; ++i)
    {
        cin >> life;
        if (life > maxLife)
            maxLife = life;
    }
    for (int i = 1; i <= n; ++i)
        for (int j = b; j >= players[i].cost; --j)
            f[j] = max(f[j], f[j - players[i].cost] + players[i].attack);
    if (f[b] == 0)
    {
        cout << -1;
        return 0;
    }
    // 向上取整函数
    cout << ceil((float)maxLife / f[b]);
}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值