HDU - 1114 Piggy-Bank(完全揹包板題)

sunlanchang發表於2019-01-31

Description

小盆友通過往豬豬存錢罐裡放錢的方式攢錢做事。存錢罐除非砸壞,否則無法把錢取出。為了知道是否攢了足夠的錢,對存錢罐稱重。然後告訴每種錢幣的重量和價值,問存錢罐裡最少可能有多少錢。

Sample Input

3
10 110
2
1 1
30 50
10 110
2
1 1
50 30
1 6
2
10 3
20 4

Sample Output

The minimum amount of money in the piggy-bank is 60.
The minimum amount of money in the piggy-bank is 100.
This is impossible.

Solution

完全揹包板題。注意恰好裝滿時候dp初始化為無窮,可以不恰好裝滿時dp初始化為0。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 11111, INF = 0x3f3f3f3f;
int dp[maxn];
int total_cost, total_kind;
struct Obj
{
    int value, cost;
};
Obj arr[maxn];
void complete_pack()
{
    for (int i = 1; i <= total_kind; i++)
        for (int j = arr[i].cost; j <= total_cost; j++)
            dp[j] = min(dp[j], dp[j - arr[i].cost] + arr[i].value);
    if (dp[total_cost] != INF)
        printf("The minimum amount of money in the piggy-bank is %d.\n", dp[total_cost]);
    else
        printf("This is impossible.\n");
}
int main()
{
    // freopen("in.txt", "r", stdin);
    int T;
    scanf("%d", &T);
    while (T--)
    {
        int E, F;
        scanf("%d%d", &E, &F);
        total_cost = F - E;
        scanf("%d", &total_kind);
        for (int i = 1; i <= total_kind; i++)
            scanf("%d%d", &arr[i].value, &arr[i].cost);
        memset(dp, 0x3f, sizeof(dp));
        dp[0] = 0;
        complete_pack();
    }
    return 0;
}

相關文章