题意:
John去买东西,东西的价格是T(1 <= T <= 10000),John所在的地方有n(1 <= n <= 100)种的硬币,面值分别为V1, V2, ..., Vn (1 <= Vi <= 120)。John带了C1枚面值为V1的硬币,C2枚面值为V2的硬币,...,Cn枚面值为Vn的硬币(0 <= Ci <= 10000)。售货员那里每种硬币都有无限多个。问为了支付这个T,John给售货员的硬币数目加上售货员找回的零钱的硬币数目最少是多少。如果无法支付T,输出-1 。
思路:
1. 和 POJ 1252 类似,只不过这次对于找零变成了完全背包,相对来说复杂度减少了一点点。
2. 问题的难点在于如何确定背包容量的上限,看到 discuss 上有人说 T + vmax * vmax 是上限,其实再把 vmax /= 2 也是可以的。
3. 多重背包 + 倍增优化是可以做的,最近在学习单调队列,顺便就用单调队列优化了下,16ms,真心膜拜 0ms 的大神。
4. 单调队列优化的时候,用 二分搜索 反而比 从后往前遍历 要慢,可能是数据的原因吧,有关单调队列的性质还有待于慢慢理解。
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXD = 10010;
const int MAXN = 150;
const int INFS = 0x3fffffff;
int dp[MAXD << 2], A[MAXD << 2], B[MAXD << 2];
int V[MAXN], C[MAXN];
void ZeroOnePack(int w, int val, int vol)
{
for (int v = vol; v >= w; --v)
if (dp[v - w] != INFS)
dp[v] = min(dp[v], dp[v - w] + val);
}
void CompletePack(int w, int val, int vol)
{
for (int v = w; v <= vol; ++v)
if (dp[v - w] != INFS)
dp[v] = min(dp[v], dp[v - w] + val);
}
inline int BinarySearch(int arr[], int l, int r, int val)
{
while (l <= r)
{
int m = (l + r) >> 1;
if (arr[m] > val)
r = m - 1;
else
l = m + 1;
}
return l - 1;
}
void MultiplePack(int w, int val, int n, int vol)
{
if (n == 1)
{
ZeroOnePack(w, val, vol);
return ;
}
if (w * n >= vol)
{
CompletePack(w, val, vol);
return ;
}
for (int rem = 0; rem < w; ++rem)
{
int la = 0, ra = -1;
int lb = 0, rb = -1;
for (int v = rem, i = 0; v <= vol; v += w, ++i)
{
if (la + n == ra && A[la] == B[lb])
++la, ++lb;
else if (la + n == ra)
++la;
++ra;
if (dp[v] != INFS)
A[ra] = dp[v] - i * val;
else
A[ra] = INFS;
//while (lb <= rb && A[ra] < B[rb])
// --rb;
if (lb <= rb)
rb = BinarySearch(B, lb, rb, A[ra]);
B[++rb] = A[ra];
dp[v] = min(dp[v], B[lb] + i * val) ;
}
}
}
int main()
{
int n, vol;
while (scanf("%d %d", &n, &vol) != EOF)
{
int vmax = 0;
for (int i = 0; i < n; ++i)
{
scanf("%d", &V[i]);
vmax = max(vmax, V[i]);
}
for (int i = 0; i < n; ++i)
scanf("%d", &C[i]);
vmax >>= 1;
vmax *= vmax;
vmax += vol;
dp[0] = 0;
for (int v = 1; v <= vmax; ++v)
dp[v] = INFS;
for (int i = 0; i < n; ++i)
MultiplePack(V[i], 1, C[i], vmax);
for (int i = 0; i < n; ++i)
for (int v = vmax - V[i]; v >= 0; --v)
dp[v] = min(dp[v], dp[v + V[i]] + 1);
if (dp[vol] != INFS)
printf("%d\n", dp[vol]);
else
printf("-1\n");
}
return 0;
}