--- 这里是 cjiaw 的小窝(●'◡'●) ---

正在玩命加载中......

AcWing 11. 背包问题求方案数

题目链接:11. 背包问题求方案数 - AcWing题库


题目大意:

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

第 i 件物品的体积是 w[i],价值是 v[i]

求解将哪些物品装入背包总价值最大。

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


思路:

  • f[j]:表示背包容量为j时,能装入的最大价值。
  • g[j]:表示背包容量为j时,能达到最大价值f[j]的方案总数。(初始状态对于任意容量 j“什么都不选”是一种方案)

代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define  mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;

const int N = 200086, mod = 1e9+7;

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

void solve() {

    cin >> n >> m;
    for (int i = 0; i <= m; i++) g[i] = 1;
    for (int i = 1; i <= n; i++) {
        int w, v;
        cin >> w >> v;
        for (int j = m; j >= w; j--) {
            if (f[j - w] + v > f[j]) {
                f[j] = f[j - w] + v;
                g[j] = g[j - w];
            } else if (f[j - w] + v == f[j]) {
                g[j] = (g[j] + g[j - w]) % mod;
            }
        }
    }
    
    cout << g[m] << endl;
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    int T = 1;
// cin >> T;
    while (T--) solve();
    
    return 0;
}

 

posted @ 2025-11-05 13:39  wwjjw  阅读(11)  评论(0)    收藏  举报