题目链接
个人思路
需要使用有限的预算 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]);
}