Hint 1
Hint 2
Hint 3
Explanation
A crucial observation is that if we can make a number , we can make any number , where k is a non-negative integer. We may be tempted to rewrite this as so: if we can make , we can make all . 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 , we can simply output . However, this solution has a flaw; try to think about why before moving on!
The issue occurs when . For example, if and , we can construct 8, but we cannot construct 2, even though . 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:
The time limit is quite tight for this problem. With and , we end up getting around operations. Here are a few optimizations I had to use:
- I use a 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 , each element should have been visited a total of times. Another alternative is simply inverting 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 's in the above editorial can be replaced with an arbitrary ; in fact, the condition that is sorted doesn't even matter. However, we choose it simply for being the smallest value, which marginally boosts execution time; using 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 has outgoing, weighted edges to with weight , for each
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 limitint 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!