AcWing 11. 背包问题求方案数
原题链接
中等
作者:
妙WA草
,
2022-07-04 16:00:59
,
所有人可见
,
阅读 169
题目描述
AcWing 11. 背包问题求方案数
C++ 代码
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int mod = 1e9 + 7;
int n,m,f[1010],g[1010],v,w;
/*
集合:f:为总体积为j的物品集合 g:为总体积为j且价值为f[j]的集合
状态:f: max g: num
*/
int main()
{
cin >> n >> m;
g[0] = 1;
for(int i = 1; i <= n; i ++)
{
cin >> v >> w;
for(int j = m; j >= v; j --)
{
int maxv = max(f[j],f[j - v] + w);//判断哪一个最大
int s = 0;
if(f[j] == maxv)s = g[j] % mod;//最大值和原来相等方案数与原来一样
if(maxv == f[j - v] + w)s = (g[j - v] + s) % mod;//新的和最大值相等,加上新方案的数量
f[j] = maxv;
g[j] = s;
}
}
int res = 0;
for(int j = 0; j <= m; j ++)
{
if(f[j] == f[m])res = (g[j] + res) % mod;
}
cout << res << endl;
return 0;
}