In the code below, x is the minimum necessary remaining milk to purchase. Because it iterates from largest deal to smallest, it never seems to have a way of updating curCost if it finds a better per-bucket-price deal at a smaller size. Can someone explain? Also, I don’t understand why you can ignore all deals greater than 2^{30} in size—I know you will never need to purchase more than one of those, but couldn’t there be a really great deal among those, like 2^{40} buckets for $1?
void solve()
{
int N, K, Q;
scanf("%d %d", &N, &Q);
int price[N];
scanf("%d", &price[0]);
for (int idx = 1; idx < N; ++idx)
{
scanf("%d", &price[idx]);
price[idx] = min(price[idx], 2 * price[idx-1]);
}
for (int idx = 0; idx < Q; ++idx)
{
int x;
scanf("%d", &x);
long long minCost = 1e18;
long long curCost = 0;
for (int jdx = min(30, N-1); jdx >= 0; --jdx)
{
int curBuckets = 1<<jdx;
long long count = x / curBuckets;
x -= count*curBuckets;
curCost += count*price[jdx];
if (x == 0)
minCost = min(minCost, curCost);
else
minCost = min(minCost, curCost + price[jdx]);
}
printf("%lld\n", minCost);
}
}