Table of Contents

ExplanationImplementation

Editorial (C++)

Explanation

Let's define dp[i][j]\text{dp}[i][j] as the number of ways to fill the first ii elements of the array, such that ai=ja_i = j.

Base case: if x1=0x_1 = 0, then the first element is unknown and can be anything from 11 to mm, so dp[1][j]=1\text{dp}[1][j] = 1 for all jj. Otherwise, the first element is fixed, so dp[1][x1]=1\text{dp}[1][x_1] = 1 and all other dp[1][j]=0\text{dp}[1][j] = 0.

For i>1i > 1, since adjacent elements differ by at most 11, ai=ja_i = j is possibly only if ai1a_{i-1} is j1j-1, jj, or j+1j+1:

dp[i][j]=dp[i1][j1]+dp[i1][j]+dp[i1][j+1]\text{dp}[i][j] = \text{dp}[i-1][j-1] + \text{dp}[i-1][j] + \text{dp}[i-1][j+1]

We can use the same idea seen in Grid Paths, where a trap cell forces dp[x][y]=0dp[x][y] = 0 since no path can end there. Then, we set dp[i][j]=0\text{dp}[i][j] = 0 whenever index ii is fixed to a value other than jj, since no valid array can have ai=ja_i = j in that case.

We compute the final answer by summing dp[n][j]\text{dp}[n][j] over all jj from 11 to mm.

Implementation

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

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!