AcWing 11. 【Java】背包问题求方案数
原题链接
中等
作者:
tt2767
,
2020-01-12 22:48:21
,
所有人可见
,
阅读 962
/*
1. 状态定义:f[j] 表示当体积恰好为j时的最大价值,g[j] 表示当体积恰好为j时的方案数
2. 状态计算:f[j] = MAX(f[j-v[i]])
g[j] += f[j] == MAX ? g[j]: 0
g[j] += f[j-v[i]] == MAX ? g[j-v[i]]: 0
3. 边界: f[0] = 0, f[~] = -INF
g[0] = 1, g[~] = 0
*/
import java.util.*;
public class Main{
void run(){
int N = jin.nextInt();
int V = jin.nextInt();
for (int i = 1 ; i <= N ; i++){
v[i] = jin.nextInt();
w[i] = jin.nextInt();
}
Arrays.fill(f, Integer.MIN_VALUE);
f[0] = 0;
g[0] = 1;
for (int i = 1 ; i <= N ; i++){
for (int j = V ; j >= v[i] ;j--){
int t = Math.max(f[j], f[j -v[i]] + w[i]); //忘记+w
int s = 0;
if (f[j] == t) s += g[j] %mod ;
if (f[j-v[i]] + w[i]== t) s+= g[j-v[i]] %mod; // 忘记+w
f[j] = t;
g[j] = s;
}
}
int maxV = 0;
int res = 0;
for (int i = 1 ; i <= V ; i++) maxV = Math.max(maxV, f[i]);
for (int i = 1 ; i <= V ; i++){
if (f[i] == maxV) res += g[i] % mod;
}
System.out.println(res);
}
int mod = 1000000007;
int maxN = 1002;
int[] w = new int[maxN];
int[] v = new int[maxN];
int[] g = new int[maxN];
int[] f = new int[maxN];
Scanner jin = new Scanner (System.in);
public static void main(String[] args) {new Main().run();}
}