Table of Contents

ExplanationImplementation

Hint 1

Hint 2

Hint 3

Explanation

A crucial observation is that if we can make a number xx, we can make any number x+ka0x + k\cdot a_0, where k is a non-negative integer. We may be tempted to rewrite this as so: if we can make xx, we can make all yxmoda0y \equiv x \mod a_0. If this is indeed the case, we can run a simple 0/1 DP to figure out what mods we can assemble, and to answer a query bib_i, we can simply output dp[bimoda0]\texttt{dp}[b_i \mod a_0]. However, this solution has a flaw; try to think about why before moving on!

The issue occurs when x>a0x > a_0. For example, if n=2n = 2 and a={3,5}a = \{3, 5\}, we can construct 8, but we cannot construct 2, even though 28moda02 \equiv 8 \mod a_0. Fortunately, this only requires a minor fix for our DP. Try to think of it yourself, but feel free to consult the below implementation if you get stuck!

Implementation

Time Complexity: O(NA)\mathcal{O}(NA)

The time limit is quite tight for this problem. With n5000n \leq 5000 and ai50000a_i \leq 50000, we end up getting around 2.5e82.5\text{e}8 operations. Here are a few optimizations I had to use:

  • I use a vis\texttt{vis} array in my implementation, and clearing it on every iteration turned out to be too slow. So instead of simply storing true/false for whether an element is visisted, I stored how many times that element had been visited across all iterations instead, taking advantage of the fact that in each iteration, all elements will be visited exactly once, thus implying that after iteration ii, each element should have been visited a total of ii times. Another alternative is simply inverting vis\texttt{vis} on each subsequent iteration: i.e. on iteration 1, false = not visited, true = visisted; but on iteration 2, false = visited, true = not visited; etc.
  • Theoretically, all the a0a_0's in the above editorial can be replaced with an arbitrary aia_i; in fact, the condition that aa is sorted doesn't even matter. However, we choose it simply for being the smallest value, which marginally boosts execution time; using a1a_1 instead actually causes TLE for the following code.

While reading the following code, it may be helpful to consider that our DP is equivalent to running a shortest-path algorithm on a graph where each node i[0,a0)i \in [0, a_0) has nn outgoing, weighted edges to (i+aj) % a0(i + a_j) \text{ \% }a_0 with weight aja_j, for each j[0,n).j \in [0, n).

C++

#include <bits/stdc++.h>
using namespace std;
const int N = 5000;
const int K = 50000;
const int INF = 1e9;
int a[N], d[K], vis[K]; // arrays and fast IO are needed for the time limit
int main() {

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!