The question is: there is a piggy bank with coins in it. I only know the weight of the coins I have saved and the coins I have not loaded, and I know the weight of each coin. The minimum possible amount in the piggy bank is required. If the coin weight in the piggy bank does not match the weight of each nominal coin, impossible is output.
Analysis: this is also a typical full backpack problem, because we can think that there are many coins of each nominal value in the piggy bank. This question is to change the maximum value to the minimum value. And the backpack must be fully filled. At this time, you must note that the initial initialization should not be negative infinity but positive infinity. But we cannot define this as follows:
[Cpp]
# Define MAX_INT 0x7fffffff
# Define MAX_INT 0x7fffffff
If this definition is used, F [] will overflow when F [v-cost] + weight is calculated, because addition is used, so pay special attention to this. We should define MAX_INT as the maximum possible value of F. F [] indicates the minimum value that can be obtained by placing an I-item into a backpack with a capacity of v. At present, the maximum value of v is 10000, and the lightest weight of the coin is 1. That is to say, there may be a maximum of 10000 coins, and the maximum nominal value of the coin is 50000. That is to say, the maximum value of F [] is 500000000. So we should
[Cpp]
# Define MAX_INT 500000000
# Define MAX_INT 500000000
See the Code:
[Cpp]
# Include <iostream>
Using namespace std;
# Define MAX_INT 50000000
Int F [10001];
Int P [501];
Int W [501];
Int min (int a, int B)
{
Return a <B? A: B;
}
Void CompletePack (int cost, int weight, int V)
{
For (int v = cost; v <= V; ++ v ){
F [v] = min (F [v], F [v-cost] + weight );
}
}
Int main (int argc, char ** argv)
{
Int T, a, B, V, n;
Cin> T;
While (T --){
Cin> a> B;
V = B-;
Cin> n;
F [0] = 0;
For (int I = 1; I <= 10000; ++ I)
F [I] = MAX_INT;
For (int I = 1; I <= n; ++ I ){
Cin> P [I]> W [I];
CompletePack (W [I], P [I], V );
}
If (F [V] = MAX_INT)
Cout <"This is impossible." <endl;
Else
Cout <"The minimum amount of money in the piggy-bank is" <F [V] <"." <endl;
}
System ("pause ");
Return 0;
}
# Include <iostream>
Using namespace std;
# Define MAX_INT 50000000
Int F [10001];
Int P [501];
Int W [501];
Int min (int a, int B)
{
Return a <B? A: B;
}
Void CompletePack (int cost, int weight, int V)
{
For (int v = cost; v <= V; ++ v ){
F [v] = min (F [v], F [v-cost] + weight );
}
}
Int main (int argc, char ** argv)
{
Int T, a, B, V, n;
Cin> T;
While (T --){
Cin> a> B;
V = B-;
Cin> n;
F [0] = 0;
For (int I = 1; I <= 10000; ++ I)
F [I] = MAX_INT;
For (int I = 1; I <= n; ++ I ){
Cin> P [I]> W [I];
CompletePack (W [I], P [I], V );
}
If (F [V] = MAX_INT)
Cout <"This is impossible." <endl;
Else
Cout <"The minimum amount of money in the piggy-bank is" <F [V] <"." <endl;
}
System ("pause ");
Return 0;
}