有 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);}