【HDOJ】1114 Piggy-Bank

时间:2022-07-08 19:26:57

DP,先将coins按照重量排序可以优化。

 #include <stdio.h>
#include <stdlib.h> #define MAXNUM 10005
#define COINNUM 505
#define MAXVAL 0x7fffffff
#define MYMIN(a, b) a<b ? a:b typedef struct {
int weight, val;
} coin_st; coin_st coins[COINNUM];
int dp[MAXNUM];
int e, f; int comp(const void *a, const void *b) {
return ((coin_st*)a)->weight - ((coin_st*)b)->weight;
} int main() {
int case_n, n;
int i, j, left; scanf("%d", &case_n);
dp[] = ;
while (case_n--) {
scanf("%d %d", &e, &f);
scanf("%d", &n);
for (i=; i<n; ++i)
scanf("%d %d", &coins[i].val, &coins[i].weight);
qsort(coins, n, sizeof(coin_st), comp); for (i=; i<=f-e; ++i) {
dp[i] = MAXVAL;
for (j=; j<n; ++j) {
left = i-coins[j].weight;
if (left<)
break;
if (dp[left]!=MAXVAL && dp[left]+coins[j].val < dp[i])
dp[i] = dp[left]+coins[j].val;
}
}
if (dp[f-e] == MAXVAL)
printf("This is impossible.\n");
else
printf("The minimum amount of money in the piggy-bank is %d.\n", dp[f-e]);
} return ;
}