背包问题求方案数量

这篇博客介绍了一个使用动态规划求解01背包问题的C++代码实现。问题中,有N件物品和一个固定容量的背包,每件物品有自己的体积vi和价值wi。目标是找到能放入背包且总价值最大的物品组合。代码通过初始化和更新dp数组来找出最优解,并计算方案数。最终输出方案数模1e9+7的结果。
摘要由CSDN通过智能技术生成

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

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

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

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

输入格式

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

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

输出格式

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

数据范围

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

输入样例

4 5
1 2
2 4
3 4
4 6

输出样例:

2

 用一个数组g[i]表示容量为i的背包最优解的方案数

#include<bits/stdc++.h>
using namespace std; using ll = long long; //using lll = __int128;
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
//快速读 快速写
//template <class T>istream& read(T& x, istream& cin = std::cin);template <class T>ostream& write(T x, ostream& cout = std::cout);ostream& operator<<(ostream& cout, lll x);istream& operator>>(istream& cin, lll &x);
bool check(int i, int j);

const int N = 1e3 + 10, mod = 1e9 + 7;

int n, m, dp[N], g[N];  //g[i]表示背包容量为i的最优解的方案数

void init() {
	cin >> n >> m;
	g[0] = 1;
	//for (int i = 0; i < n; i ++) {  }

	//	cout << "初始化完成\n";
	return;
}

void solve() {
	int v, w;
	while (n--) {
		cin >> v >> w;
		for (int i = m; i >= v; i--) {
			int j = dp[i - v] + w;
			if (j > dp[i]) g[i] = g[i - v] % mod;  //如果当前物品放入背包更优则方案数跟新为g[i - v]
			else if (dp[i] == j) g[i] = (g[i - v] + g[i]) % mod;  //如果当前物品放入与不放入无影响,则把两种的方案数相加
			dp[i] = max(dp[i], j);
		}
	}
	// dp[m]为最优方案
	int cnt = g[m];
	for (int i = m; i; i--)  // 遍历最后所有最优方案
		if (dp[i - 1] == dp[i])
			cnt = (cnt + g[i - 1]) % mod;
		else
			break;
	cout << cnt % mod;
	return;
}

int main(void) {
	ios::sync_with_stdio(0); cin.tie(0); cout << setprecision(6) << fixed;//保留6位小数从小数点后计数
	int _T = 1;
	//cin >> _T;
	while (_T--) {
		init(); solve();
		cout << "\n";
	}
	return 0;
}
//template <class T> istream& read(T& x, istream& cin) {T num = 0; bool f = 0; char ch = 0;while (!isdigit(ch)) { f |= ch == '-'; if (!cin.get(ch)) return cin; }while (isdigit(ch)) { num = (num << 3) + (num << 1) + (ch ^ 48); if (!cin.get(ch)) return cin; }x = f ? -num : num; return cin;}
//template <class T> ostream& write(T x, ostream& cout) {if (x < 0) cout.put('-'), x = -x;if (x > 9) write(x / 10);cout.put(x % 10 + '0'); return cout;}
//ostream& operator<<(ostream& cout, lll x) {write(x);return cout;}istream& operator>>(istream& cin, lll &x) {return read(x);}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值