hdu 2126 Buy the souvenirs 【输出方案数】【01背包】(经典)

题目链接:https://vjudge.net/contest/103424#problem/K

题目大意:

给n个物品,和m块钱,输出能够购买最多物品的个数和购买这么多物品的方案数。

#include <cstring>
#include <iostream>
#include <algorithm>
#define clr(a) (memset(a,0,sizeof(a)))
using namespace std;
int dp[510][50], a[50];
int n, m;
int main()
{
    int T;
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d %d", &n, &m);
        for (int i = 1; i <= n; i++)scanf("%d", &a[i]);
        clr(dp);
        dp[0][0] = 1;
        int mx = 0;
        for (int i = 1; i <= n; i++)
            for (int j = m; j >= a[i]; j--)
            {
                for (int k = n - 1; k >= 0; k--)
                {
                    if (dp[j - a[i]][k])dp[j][k + 1] += dp[j - a[i]][k];      
                    mx = max(mx, k + 1);             //mx为最多能买几件物品
                }
            }
        if (mx == 0)
        {
            puts("Sorry, you can't buy anything.");
            continue;
        }
        int ans = 0;           //ans为能够买mx件物品的选择方案总数(mx为最多能购买的物品数量)
        for (int i = 0; i <= m; i++)ans += dp[i][mx];
        printf("You have %d selection(s) to buy with %d kind(s) of souvenirs.\n", ans, mx);
    }
    return 0;
}

 2018-05-21

猜你喜欢

转载自www.cnblogs.com/00isok/p/9069929.html