AcWing 11. 背包问题求方案数
原题链接
中等
作者:
不知名的fE
,
2024-12-08 22:41:01
,
所有人可见
,
阅读 1
import java.util.*;
public class Main {
static final int N = 1010, Mod = (int)1e9 + 7;
static int[][] f = new int[N][N], g = new int[N][N];
static int[] v = new int[N], w = new int[N];
static int n, m;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt(); m = sc.nextInt();
for (int i = 1; i <= n; i++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
for (int j = 0; j <= m; j++) g[j][0] = 1;//直接写g[0][0]也是对的
for (int i = 1; i <= n; i++)
for (int j = 0; j <= m; j++) {//需要从0开始枚举,g[i][0]是有意义的
int t = f[i - 1][j];
int cnt = 0;
if (j >= v[i]) {
t = Math.max(t, f[i - 1][j - v[i]] + w[i]);
if (t == f[i - 1][j - v[i]] + w[i]) cnt += g[i - 1][j - v[i]];
}
if (t == f[i - 1][j]) cnt += g[i - 1][j];
g[i][j] = cnt % Mod;
f[i][j] = t;
}
int ans = 0;
for (int j = 0; j <= m; j++)
if (f[n][m] == f[n][j])
ans = (ans + g[n][j]) % Mod;
System.out.println(ans);
}
}
import java.util.*;
public class Main {
static final int N = 1010, Mod = (int)1e9 + 7;
static int[] f = new int[N], g = new int[N];
static int[] v = new int[N], w = new int[N];
static int n, m;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt(); m = sc.nextInt();
for (int i = 1; i <= n; i++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
g[0] = 1;
for (int i = 1; i <= n; i++)
for (int j = m; j >= v[i]; j--) {
int cnt = 0, max;
max = Math.max(f[j], f[j - v[i]] + w[i]);
if (max == f[j - v[i]] + w[i]) cnt += g[j - v[i]];
if (max == f[j]) cnt += g[j];
g[j] = cnt % Mod;
f[j] = max;
}
int res = 0;
for (int j = 0; j <= m; j++)
if (res < f[j]) res = f[j];
int ans = 0;
for (int j = 0; j <= m; j++)
if (res == f[j]) ans = (ans + g[j]) % Mod;
System.out.println(ans);
}
}