poj1384

dp

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;

#define MAX_COIN_NUM 505
#define MAX_CAP 10005

struct Coin
{
    int price, weight;
}coin[MAX_COIN_NUM];

int capacity;
int coin_num;
int f[MAX_CAP]; 

void input()
{
    int a, b;
    scanf("%d%d", &a, &b);
    capacity = b - a;
    scanf("%d", &coin_num);
    for (int i = 0; i < coin_num; i++)
        scanf("%d%d", &coin[i].price, &coin[i].weight);
}

void work()
{
    memset(f, -1, sizeof(f));
    f[0] = 0;
    for (int i = 0; i < coin_num; i++)
        for (int j = coin[i].weight; j <= capacity; j++)
            if (f[j - coin[i].weight] != -1)
            {
                int temp = f[j - coin[i].weight] + coin[i].price;
                if (f[j] == -1 || f[j] > temp)
                    f[j] = temp;
            }
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        input();
        work();
        if (f[capacity] == -1)
            printf("This is impossible.\n");
        else
            printf("The minimum amount of money in the piggy-bank is %d.\n", f[capacity]);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/rainydays/p/3132740.html