Coin Combinations and Queries

For each query, count the multisets of at most d_i coins of denomination c_i (i=1..4) that sum to exactly v; answers fit in 64-bit.

Hard8Dynamic programmingCombinatoricsMathImplementationNo attempts yetTime limit3sMemory limit512 MB

Problem

A country issues coins of exactly four denominations, worth c1c_1, c2c_2, c3c_3 and c4c_4 won. Your wallet holds d1d_1 coins worth c1c_1 won, d2d_2 coins worth c2c_2 won, d3d_3 coins worth c3c_3 won and d4d_4 coins worth c4c_4 won. Write a program that counts the ways to pay exactly vv won with those coins.

Coins of the same denomination are not distinguished. Two ways are the same when they use the same number of coins of every denomination.

For example, with three 1 won coins, two 2 won coins, three 5 won coins and one 10 won coin, there are four ways to pay 10 won.

  • 10=1+1+1+2+510 = 1 + 1 + 1 + 2 + 5
  • 10=1+2+2+510 = 1 + 2 + 2 + 5
  • 10=5+510 = 5 + 5
  • 10=1010 = 10

Input

The first line contains the number of test cases TT. (1T1001 \le T \le 100)

The first line of each test case contains the integers c1c_1, c2c_2, c3c_3, c4c_4, qq separated by spaces. (1c1<c2<c3<c410001 \le c_1 < c_2 < c_3 < c_4 \le 1000, 1q1001 \le q \le 100)

Each of the next qq lines contains one query, made of the integers d1d_1, d2d_2, d3d_3, d4d_4, vv. (1d1,d2,d3,d4,v1051 \le d_1, d_2, d_3, d_4, v \le 10^5)

Output

For each query, print on its own line the number of ways to pay exactly vv won using at most d1d_1 coins of c1c_1 won, at most d2d_2 coins of c2c_2 won, at most d3d_3 coins of c3c_3 won and at most d4d_4 coins of c4c_4 won. Print 0 when no way exists. The answer can exceed the range of a 32-bit integer.