Post

AcWing11 - 背包问题求方案数

有 N 件物品和一个容量是 V 的背包。每件物品只能使用一次。

第 i 件物品的体积是 vi,价值是 wi。

求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。

输出 最优选法的方案数。注意答案可能很大,请输出答案模 109+7 的结果。

输入格式

第一行两个整数,N,V,用空格隔开,分别表示物品数量和背包容积。

接下来有 N 行,每行两个整数 vi,wi,用空格隔开,分别表示第 i 件物品的体积和价值。

输出格式

输出一个整数,表示 方案数 模 109+7 的结果。

数据范围

0<N,V≤1000 0<vi,wi≤1000

输入样例

1
2
3
4
5
4 5
1 2
2 4
3 4
4 6

输出样例:

1
2

新开一个数组记录方案数,并将状态表示改为体积恰好是j的方案数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010, mod = 1e9 + 7;

int n, m;
int f[N], g[N];

int main() {
  cin >> n >> m;
  memset(f, 0x8f, sizeof f);
  f[0] = 0;
  g[0] = 1;
  
  for (int i = 0; i < n; i++) {
    int v, w;
    cin >> v >> w;
    for (int j = m; j >= v; j--) {
      int maxv = max(f[j], f[j - v] + w);
      int cnt = 0;
      if (maxv == f[j]) cnt += g[j];
      if (maxv == f[j - v] + w) cnt += g[j - v];
      g[j] = cnt % mod;
      f[j] = maxv;
    }
  }
  
  int res = 0;
  for (int i = 0; i <= m; i++) res = max(res, f[i]); // 因为这里状态定义为恰好,需要遍历找最大值
  int cnt = 0;
  for (int i = 0; i <= m; i++)
    if (res == f[i])
      cnt = (cnt + g[i]) % mod;
  cout << cnt << endl;
  return 0;
}
This post is licensed under CC BY 4.0 by the author.