【杭电oj】2126 - Buy the souvenirs(01背包方案数)

题目

d p [ i ] [ j ] i j

AC代码:

#include<bits/stdc++.h>
using namespace std;

int a[33],dp[33][555];      //dp[i][j]表示买i个物品花j元的种类数 
int main(){
    int T,n,v;
    cin>>T;
    while(T--){
        cin>>n>>v;
        for(int i=1;i<=n;++i)   cin>>a[i];
        memset(dp,0,sizeof(dp));
        dp[0][0] = 1;
        int mmax = 0,ans = 0;
        for(int i=1;i<=n;++i){
            for(int j=v;j>=a[i];--j){
                for(int k=i;k>=1;--k){
                    if(dp[k-1][j-a[i]]){
                        dp[k][j] += dp[k-1][j-a[i]];
                        mmax = max(mmax,k);   //更新最大可选择的个数
                    }
                }
            }
        }
        for(int i=0;i<=v;++i)   ans += dp[mmax][i];    //统计组合数
        if(mmax)    printf("You have %d selection(s) to buy with %d kind(s) of souvenirs.\n",ans,mmax);
        else    printf("Sorry, you can't buy anything.\n");
    }
    return 0;
} 
/*
2
4 7
1 2 3 4

4 0
1 2 3 4
*/

猜你喜欢

转载自blog.csdn.net/qq_41009682/article/details/81511914