---
id: 1074
lang: en
translation_of: index.md
source_sha256: 5a44728ee77e6d177287f8c0e0f8972179f8676a4e3d5a8aacfa588d02986bab
title: "P1450: [HAOI2008] Coin Shopping — Solution"
description: "First consider the unrestricted version, ignoring the coin-count limits in the queries; an unbounded knapsack handles it in linear time."
tags: ["OI","Math","Inclusion–Exclusion"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 硬币购物 rendered as “Coin Shopping”."
  - "The casual verb 搞 (搞一搞, 搞成, 搞个) is rendered as plain informal English (“hack at it”, “turn into”, “do”) with no chip, as in other approved editions."
---

## Main Idea

Let’s first consider the unrestricted version, that is, ignoring the coin-count limits in the queries. We can just hack at it with an unbounded knapsack, and the complexity is linear.

```cpp
dp[0] = 1;
for (int i = 0; i < 4; i++)
    for (int j = ci[i]; j < MAX_N; j++)
        dp[j] += dp[j - ci[i]];
```

<!--more-->

So how do we answer queries with low complexity? We can consider the inclusion–exclusion principle and turn the answer into:

$$
dp[s] - dp[s-(d_{1}+1)*c_{1}] - dp[s-(d_{2}+1)*c_{2}] - dp[s-(d_{3}+1)*c_{3}] - dp[s-(d_{4}+1)*c_{4}] + dp[s-(d_{1}+1)*c_{1}-(d_{2}+1)*c_{2}] + dp[s-(d_{1}+1)*c_{1}-(d_{3}+1)*c_{3}] + dp[s-(d_{1}+1)*c_{1}-(d_{4}+1)*c_{4}] \dots
$$

Then just do the inclusion–exclusion using binary and that’s it:

```cpp
// P1450.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 101000;
int ci[5], tot, di[5], si;
ll dp[101000];
int main()
{
    for (int i = 0; i < 4; i++)
        scanf("%d", &ci[i]);
    dp[0] = 1;
    for (int i = 0; i < 4; i++)
        for (int j = ci[i]; j < MAX_N; j++)
            dp[j] += dp[j - ci[i]];
    scanf("%d", &tot);
    while (tot--)
    {
        for (int j = 0; j < 4; j++)
            scanf("%d", &di[j]);
        scanf("%d", &si);
        ll ans = 0;
        for (int i = 0; i < 16; i++)
        {
            ll C = si, T = 0;
            for (int j = 0; j < 4; j++)
                if ((i >> j) & 1)
                    C -= (di[j] + 1) * ci[j], T ^= 1;
            if (C < 0)
                continue;
            ans += (T ? -1 : 1) * dp[C];
        }
        printf("%lld\n", ans);
    }
    return 0;
}
```
