HDU 2126 Buy the souvenirs 01背包 输出方案数

来源:互联网 发布:微信淘客发单软件 编辑:程序博客网 时间:2024/04/26 16:24

题意:有N种纪念品,给出对应的价格。现在有N元钱,想买到最多的纪念品,同时输出所有可能的方案数。

思路:因为纪念品可以买,也可以不买。所以是标准的01背包。

           在求最大值的过程中,同时求出对应的方案数即可。注意方案数的计算。

代码如下:

#include <cstdio>#include <algorithm>#include <cstring>using namespace std;int a[50];int dp[550][2];int main(void){    //freopen("input.txt","r",stdin);    int T,N,M;    scanf("%d",&T);    while(T--){        scanf("%d%d",&N,&M);        for(int i = 0; i < N; ++i)            scanf("%d",&a[i]);        for(int i = 0; i <= M; ++i)            dp[i][1] = 1,dp[i][0] = 0;        for(int i = 0; i < N; ++i){            for(int j = M; j >= a[i]; --j){                if(dp[j][0] < dp[j - a[i]][0] + 1){                    dp[j][0] = dp[j-a[i]][0] + 1;                    dp[j][1] = dp[j-a[i]][1];                }                else if(dp[j][0] == dp[j - a[i]][0] + 1)                    dp[j][1] += dp[j-a[i]][1];            }//            for(int j = 0; j <= M; ++j)//                printf("%d%c",dp[j][1],j == M?'\n':' ');        }        if(dp[M][0] == 0)            puts("Sorry, you can't buy anything.");        else            printf("You have %d selection(s) to buy with %d kind(s) of souvenirs.\n",dp[M][1],dp[M][0]);    }    return 0;}

0 0
原创粉丝点击