0w1

Yuki 42 貯金箱の溜息

Problem Description:
There are 6 kinds of coins, with units 1, 5, 10, 50, 100, 500, respectively. You have infinite number of each of them. You are to deal with T test cases, and in each case you will be given a value M, where you should output the number of ways to prepare the coins such that the sum of values is exactly M, modulo 1e9 + 9.

Constraints:
1 ≤ T ≤ 10000
1 ≤ M[k] ≤ 1e18

Solution:
Disregarding the large constraint, we can come up with the classic infinite knapsack algorithm:
dp[i][j]: With the first i coins, number of ways to prepare sum of j.
dp[i][j] = dp[i][j - C[i]] + dp[i - 1][j]
= dp[i - 1][q * C[i] + r], for all integer q, r, such that q * C[i] + r = j
Since C[i] is a multiple of C[i - 1] for all i, and dp[0][t] = 1, for any t, and dp[i][q * C[i] + r] = (1..q).map { |k| dp[i - 1][k * C[i] + r] } .sum + dp[i][r], by induction we can observe that dp[i][q * C[i] + r] can be expressed as a polynomial of q with highest power of i. Since there are only 6 kinds of coins, we can use Lagrange's interpolation to find out coefficient of each term. (Since M is given, q and r can be determined, and we will only need to plot for f(i) = i * C[5] + r, for each 0..5 === i, i.e., preprocessing of dp[0...3000] is necessary.

#include <bits/stdc++.h>
using namespace std;

const int MOD = int(1e9) + 9;
const int COIN[] = { 1, 5, 10, 50, 100, 500 };

int dp[3000];

int inv_mod(int v, int mod = MOD) {
  int res = 1;
  for (int i = mod - 2; i; i >>= 1) {
    if (i & 1) res = 1LL * res * v % mod;
    v = 1LL * v * v % mod;
  }
  return res;
}

long long solve(long long m) {
  long long res = 0;
  long long q = m / 500, r = m % 500;
  for (int i = 0; i < 6; ++i) {
    long long coe = 1;
    for (int j = 0; j < 6; ++j) {
      if (i == j) continue;
      coe = coe * (MOD + (q - j) % MOD) % MOD;
    }
    for (int j = 0; j < 6; ++j) {
      if (i == j) continue;
      coe = coe * (MOD + inv_mod(i - j) % MOD) % MOD;
    }
    (res += coe * dp[i * 500 + r] % MOD) %= MOD;
  }
  return res;
}

signed main() {
  ios::sync_with_stdio(false);
  dp[0] = 1;
  for (int i = 0; i < 6; ++i) {
    for (int j = 0; j + COIN[i] < 3000; ++j) {
      (dp[j + COIN[i]] += dp[j]) %= MOD;
    }
  }
  int T;
  cin >> T;
  while (T--) {
    long long M;
    cin >> M;
    cout << solve(M) << endl;
  }
  return 0;
}