P - Piggy-Bank
题意:存钱罐中存了好多硬币,已知空存钱罐的重量和装满钱的存钱罐重量,以及n种硬币的价值和重量,求出存钱罐中至少存了多少钱;
每种硬币的数量是无穷的,所以是个完全背包问题,求至少存了多少钱,是求最小值问题,和以往的最大值问题有所不同,初始化dp[i]为无穷大,dp[0]=0;状态转移方程为dp[i]=min(dp[i], dp[i-w[i]]+p[i]);
#include <bits/stdc++.h> using namespace std; const int maxn=10100; const int INF=0x3f3f3f3f; int E, F, n; int dp[maxn]; int p[510], w[510]; int main(){ int T; scanf("%d", &T); while(T--){ scanf("%d%d", &E, &F); int V=F-E; scanf("%d", &n); for(int i=0; i<n; i++){ scanf("%d%d", &p[i], &w[i]); } memset(dp, INF, sizeof(dp)); dp[0]=0; for(int i=0; i<n; i++){ for(int j=w[i]; j<=V; j++){ dp[j]=min(dp[j], dp[j-w[i]]+p[i]); } } if(dp[V]>=INF) printf("This is impossible.\n"); else printf("The minimum amount of money in the piggy-bank is %d.\n", dp[V]); } return 0; }