Piggy-Bank
Topic meaning:
T sets of data, each set of data has an n, representing n types of coins, first give you E, F, and then FE represents the total weight that the backpack can hold, and the value of n coins is given below and weight , Unlimited number of each, ask what is the minimum value of the backpack coins that can accommodate the weight of FE. If not, output This is impossible.
data range:
Problem solving ideas:
The meaning of the question can be simplified as, the minimum value of a knapsack filled with W weight of n kinds of items, each with an infinite number, this is a complete knapsack problem, dp[j] represents the minimum value of a knapsack with a load of j, and the transfer equation is :
See the code for details
AC code:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 10000;
const int INF = 1e9 + 7;
int dp[maxn + 5];
int E, F, W;
int T, n;
int w[505], v[505];
int main() {
scanf("%d", &T);
while(T--) {
for(int i = 0; i <= maxn; i++)dp[i] = INF;//初始化为无穷大
scanf("%d%d", &E, &F);
W = F - E;//背包大小
scanf("%d", &n);
for(int i = 1; i <= n; i++)scanf("%d%d", &w[i], &v[i]);
dp[0] = 0;
for(int i = 1; i <= n; i++) {//虽然每个物体有无限个,但是对于第i个物体,dp[j]可由dp[j-v[i]]转移过来,就达到了取任意多个第i种物体之后的状态
for(int j = v[i]; j <= W; j++) {
dp[j] = min(dp[j], dp[j - v[i]] + w[i]);
}
}
if(dp[W] == INF)printf("This is impossible.\n");//如果值未改变,说明不存在该状态
else printf("The minimum amount of money in the piggy-bank is %d.\n", dp[W]);
}
return 0;
}