1. 程式人生 > >hdu 2126 Buy the souvenirs 【輸出方案數】【01背包】(經典)

hdu 2126 Buy the souvenirs 【輸出方案數】【01背包】(經典)

continue with election i++ targe ref https contest col

題目鏈接: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

hdu 2126 Buy the souvenirs 【輸出方案數】【01背包】(經典)