HDU-3591 The trouble of Xiaoqian 组合背包问题

In the country of ALPC , Xiaoqian is a very famous mathematician. She is immersed in calculate, and she want to use the minimum number of coins in every shopping. (The numbers of the shopping include the coins she gave the store and the store backed to her.)
And now , Xiaoqian wants to buy T (1 ≤ T ≤ 10,000) cents of supplies. The currency system has N (1 ≤ N ≤ 100) different coins, with values V1, V2, …, VN (1 ≤ Vi ≤ 120). Xiaoqian is carrying C1 coins of value V1, C2 coins of value V2, …, and CN coins of value VN (0 ≤ Ci ≤ 10,000). The shopkeeper has an unlimited supply of all the coins, and always makes change in the most efficient manner .But Xiaoqian is a low-pitched girl , she wouldn’t like giving out more than 20000 once.
Input
There are several test cases in the input.
Line 1: Two space-separated integers: N and T.
Line 2: N space-separated integers, respectively V1, V2, …, VN coins (V1, …VN)
Line 3: N space-separated integers, respectively C1, C2, …, CN
The end of the input is a double 0.
Output
Output one line for each test case like this ”Case X: Y” : X presents the Xth test case and Y presents the minimum number of coins . If it is impossible to pay and receive exact change, output -1.
Sample Input
3 70
5 25 50
5 2 1
0 0
Sample Output
Case 1: 3

题目大意:有几种硬币面值,找一种解决方案使得付钱找钱两个过程经受手中的硬币数量最少。
思路:付钱过程手里每种面值的硬币数量有限,是多重背包。找钱过程每种面值的硬币数量无限,所以是完全背包。两个过程加起来即可。

AC代码

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int val[5005];
int dp[255555];

int main() {
    int n,l, sum;
    while (cin>>n && n) {
        memset(val, 0, sizeof(val));
        memset(dp, 0, sizeof(dp));
        l = 0;
        sum = 0;
        for (int i = 0; i < n; i++) {
            int a,b;
            cin>>a>>b;
            while (b--) {
                val[l++] = a;
                sum += a;
            }
        }
        for (int i = 0; i < l; i++) {
            for (int j = sum / 2; j >= val[i]; j--) {
                dp[j] = max(dp[j], dp[j - val[i]] + val[i]);
            }
        }
        cout<<sum - dp[sum / 2]<<" "<<dp[sum / 2]);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42764823/article/details/88615341