[UVA 11517] Exact Change (背包DP)

来源:互联网 发布:外文电子图书数据库有 编辑:程序博客网 时间:2024/04/24 10:52

When travelling to remote locations, it is often helpful to bring cash, in case you want to buy something from someone who does not accept credit or debit cards. It is also helpful to bring a variety of denominations in case the seller does not have change. Even so, you may not have the exact amount,and will have to pay a little bit more than full price. The same problem can arise even in urban locations, for example with vending machines that do not return change.

Of course, you would like to minimize the amount you pay (though you must pay at least as much as the value of the item). Moreover, while paying the minimum amount, you would like to minimize the number of coins or bills that you pay out.

Input

The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing an integer, the price in cents of the item you would like to buy. The price will not exceed 10 000 cents (i.e., $100). The following line contains a single integer n, the number of bills and coins that you have. The number n is at most 100. The following n lines each contain one integer, the value in cents of each bill or coin that you have. Note that the denominations can be any number of cents; they are not limited to the values of coins and bills that we usually use in Canada.However, no bill or coin will have a value greater than 10 000 cents ($100). The total value of your bills and coins will always be equal to or greater than the price of the item.

Output

For each test case, output a single line containing two integers: the total amount paid (in cents), andthe total number of coins and bills used.

Sample Input

1

1400

3

500

1000

2000

Sample Output

1500 2


要使得钱数在超过价钱的情况下尽量小,并且钞票张数尽量小。看起来像是个背包DP,但是正着不好考虑,所以倒过来做。把总价钱sum减去物品价钱tot,得到的conta当做背包容量。求不超过conta的情况下的钱数尽量大,而且用的钞票数尽量多,最后减一下既得答案。


时间是100*1000000的,比较紧张。但是用上滚动数组,然后容量那维逆着推就能过。因为价钱可能比较大,逆着推能节省不少 j - inpt[ i ] <0 的时间。


#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>using namespace std;inline int maxx(int a, int b){return a>b ? a: b;}int T,n,tot;int inpt[110];int dp[1000010];int un[1000010];int main(){scanf("%d", &T);while(T--){int sum = 0;memset(dp, 0, sizeof(dp));memset(un, 0, sizeof(un));scanf("%d%d", &tot, &n);for(int i=1; i<=n; i++){scanf("%d", &inpt[i]);sum += inpt[i];}int conta = sum - tot;for(int i=1; i<=n; i++){for(int j=conta; j>=inpt[i]; j--){if(dp[j] <= dp[j-inpt[i]]+inpt[i]){if(dp[j] == dp[j-inpt[i]]+inpt[i])un[j] = maxx(un[j], un[j-inpt[i]]+1);elseun[j] = un[j-inpt[i]]+1;dp[j] = dp[j-inpt[i]]+inpt[i];}}}printf("%d %d\n", sum-dp[conta], n-un[conta]);}return 0;}


0 0
原创粉丝点击