Explanation
Let's define as the number of ways to fill the first elements of the array, such that .
Base case: if , then the first element is unknown and can be anything from to , so for all . Otherwise, the first element is fixed, so and all other .
For , since adjacent elements differ by at most , is possibly only if is , , or :
We can use the same idea seen in Grid Paths, where a trap cell forces since no path can end there. Then, we set whenever index is fixed to a value other than , since no valid array can have in that case.
We compute the final answer by summing over all from to .
Implementation
Time Complexity:
import java.io.*;import java.util.*;public class ArrayDesc {public static final int MOD = (int)1e9 + 7;public static void main(String args[]) throws IOException {BufferedReader r = new BufferedReader(new InputStreamReader(System.in));StringTokenizer st = new StringTokenizer(r.readLine());int N = Integer.parseInt(st.nextToken());int M = Integer.parseInt(st.nextToken());
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!