一些不同类型的物品,每种物品有可取个数的上限( a[i] )

从中挑m个,求方案个数

这是背包问题?

考虑前 i 种物品,f[i][j] 表示方案个数, j 表示第i个物品取多少

 f[i][j]+= f[i-1][j-k]        f[0][0]=1


#include <iostream>
using namespace std;
const int N=103;
const int mod=1e6+7;
 #define int long long
 int f[N][N],a[N],n,m;
 
 signed main(){
    int i,j,k;
    cin>>n>>m;
    for(i=1;i<=n;i++) cin>>a[i];
    
    f[0][0]=1;
    for(i=1;i<=n;i++)
     for(j=0;j<=m;j++)
      for(k=0;k<=j&&k<=a[i];k++)
	f[i][j]+=f[i-1][j-k],f[i][j]%=mod; 
     
     cout<<f[n][m];
 }

滚动数组优化空间

注意开始 f[t][j] 时初始化为0 ,因为其保存着之前的计算结果


#include <iostream>
using namespace std;
const int N=103;
const int mod=1e6+7;
 #define int long long
 int f[2][N],a[N],n,m;
 
 signed main(){
    int i,j,k;
    cin>>n>>m;
    for(i=1;i<=n;i++) cin>>a[i];
    
    f[0][0]=1;
    for(i=1;i<=n;i++){
	    int t=i&1;
       for(j=0;j<=m;j++){ 
       		f[t][j]=0;
           for(k=0;k<=j&&k<=a[i];k++)
      	   f[t][j]+=f[t^1][j-k],f[t][j]%=mod;
	   }
	}
     cout<<f[n&1][m];
 }
 
 

posted on 2022-10-19 15:06  towboat  阅读(14)  评论(0)    收藏  举报