背包问题求解方案数目

这个问题主要是在01背包上进行进行修改,添加一个一维数组:

代码如下:

#include<iostream>
#include<cmath>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int N=1005;
const int mod=1e+7;
const int inf=-10000;
int f[N],g[N];
int n,m;
int main()
{
    int themax;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    g[i]=1;
    for(int i=1;i<=n;i++)
    {
        int v,w;
        cin>>v>>w;
        int t=0;
        for(int j=m;j>=v;j++)
        {
            int s=0;
            t=max(f[j],f[j-v]+w);
            if(t==f[j])
            {
                s+=g[j];
            }
            if(t==(f[j-v]+w))
            {
                s+=g[j-v];
            }
            if(s>mod)s-=mod;
            g[j]=s;
            f[j]=t;
        }
    }
    cout<<g[m];
}

 

posted @ 2020-08-01 17:20  喜欢爬的孩子  阅读(244)  评论(0编辑  收藏  举报