Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 5599 | Accepted: 1688 |
Description
Farmer John has gone to town to buy some farm supplies. Being a very efficient man, he always pays for his goods in such a way that the smallest number of coins changes hands, i.e., the number of coins he uses to pay plus the number of coins he receives in change is minimized. Help him to determine what this minimum number is.
FJ 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). Farmer John is carrying C1coins 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 (although Farmer John must be sure to pay in a way that makes it possible to make the correct change).
Input
Line 2: N space-separated integers, respectively V 1, V 2, ..., VN coins ( V 1, ... VN)
Line 3: N space-separated integers, respectively C 1, C 2, ..., CN
Output
Sample Input
3 70 5 25 50 5 2 1
Sample Output
3
Hint
Source
//f1[i]表示支付i元所需的最小硬币数
//f2[i]表示找i元所需的最小硬币数
//买T元东西所需的最小硬币数为f1[T + i] - f2[i]
//f1[i] = min(f1[i], f1[i - k] + 1)
//f2[i] = min(f2[i], f2[i - k] + 1)
//其中f1[i]多重背包,用二进制拆分求解
//f2[i]为完全背包
//其中:给钱上界为:T+maxValue^2,其中maxValue为最大硬币面值。
//证明:反证法。假设存在一种支付方案,John给的钱超过T+maxValue^2,
//则售货员找零超过maxValue^2,则找的硬币数目超过maxValue个,将其看作一数列,
//求前n项和sum(n),根据鸽巢原理,至少有两 个对maxValue求模的值相等,
//假设为sum(i)和sum(j),i<j,则i+1...j的硬币面值和为maxValue的倍数,
//同理,John给的钱中也有 一定数量的硬币面值和为maxValue的倍数,
//则这两堆硬币可用数量更少的maxValue面值硬币代替,产生更优方案。
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
const int MAXN = 101;
const int MAXT = 10000 + 120 * 120 + 1;
const int INF = 200000000;
int f1[MAXT];
int f2[MAXT];
int v[MAXN];
int c[MAXN];
int main() {
//freopen("1.txt", "r", stdin);
int n, T;
while(cin >> n >> T) {
int maxV = 0;
for(int i = 0; i < n; i++) {
cin >> v[i];
maxV = max(maxV, v[i]);
}
maxV *= maxV;
int maxT = T + maxV;
for(int i = 0; i < n; i++)
cin >> c[i];
for(int i = 0; i <= maxT; i++)
f1[i] = f2[i] = INF;
f1[0] = f2[0] = 0;
//完全背包求解
for(int i = 0; i < n; i++) {
for(int j = v[i]; j < maxV; j++) {
f2[j] = min(f2[j], f2[j - v[i]] + 1);
}
}
//多重背包求解
for(int i = 0; i < n; i++) {
int k = 1;
int sum = 0;
while(sum < c[i]) {
for(int j = maxT; j >= v[i] * k; j--) {
f1[j] = min(f1[j], f1[j - v[i] * k] + k);
}
sum += k;
if(sum + k * 2 > c[i])
k = c[i] - sum;
else
k *= 2;
}
}
int _min = INF;
for(int i = T; i <= maxT; i++) {
_min = min(_min, f1[i] + f2[i - T]);
}
if(_min == INF)
printf("-1/n");
else
printf("%d/n", _min);
}
return 0;
}