🍑 算法题解专栏
🍑 题目链接
输入
3
4
20 10 1
5 30 5
100 30 1
5 80 60
3
10 4 1000
10 3 1000
10 8 1000
2
12 300 50
5 200 0
输出
Case #1: 105
Case #2: 8
Case #3: 500
🍑 01背包 + 推公式
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
static int N = 110;
static int S = 100010;
static int[] f = new int[S];
static Stone[] a = new Stone[N];
static class Stone // implements Comparable<Stone>
{
int s;
int e;
int l;
public Stone(int s, int e, int l)
{
super();
this.s = s;
this.e = e;
this.l = l;
}
// @Override
// public int compareTo(Stone o)
// {
// return this.s * o.l - o.s * this.l;
// }
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int C = 1; C <= T; C++)
{
Arrays.fill(f, -0x3f3f3f3f);
int n = sc.nextInt();
int m = 0;
for (int i = 1; i <= n; i++)
{
int s = sc.nextInt();
int e = sc.nextInt();
int l = sc.nextInt();
m += s;
a[i] = new Stone(s, e, l);
}
// Arrays.sort(a, 1, n + 1, (o1, o2) -> o1.s * o2.l - o2.s * o1.s);
Arrays.sort(a, 1, n + 1, (o1, o2) -> Integer.compare(o1.s * o2.l, o2.s * o1.l));
f[0] = 0;
for (int i = 1; i <= n; i++)//枚举物品
for (int j = m; j >= a[i].s; j--)//枚举体积
f[j] = Math.max(f[j], f[j - a[i].s] + a[i].e - ((j - a[i].s) * a[i].l));
int res = 0;
for (int i = 1; i <= m; i++)
res = Math.max(res, f[i]);
System.out.println("Case #" + C + ": " + res);
}
}
}
👨🏫 大佬题解