Two arrays#11725

Two arrays (Çözgüdiň düşündirişi)

Let us consider the combined sequence:

a_1, a_2, ..., a_m, b_m, b_{m - 1}, ..., b_1

Its length is . From the problem conditions, it follows that this sequence:

Thus, the problem reduces to counting the number of nondecreasing sequences

1 \le x_1 \le x_2 \le ... \le x_{2m} \le n

Let us perform a change of variables:

y_1 = x_1 - 1, \\ y_2 = x_2 - x_1, \\ y_3 = x_3 - x_2, \\ ..., \\ y_{2m} = x_{2m} - x_{2m-1}, \\ y_{2m+1} = n - x_{2m}

Then all y_i \ge 0, and their sum is

y_1 + y_2 + ... + y_{2m} + y_{2m+1} = n - 1

Therefore, the problem reduces to counting the number of ways to decompose the number n - 1 into 2m + 1 non-negative integers. Each such decomposition corresponds to exactly one nondecreasing sequence x_1, x_2, ..., x_{2m}, and hence to exactly one pair of arrays .

By the classical formula for combinations with repetition, the number of such decompositions is C_{n+2m-1}^{2m} (see Eolymp problem ).

Example

In the first test, there are valid variants:

The corresponding combined sequence satisfies the inequalities

1 \le a_1 \le a_2 \le b_2 \le b_1 \le 2

Let us perform a change of variables:

y_1 = a_1 - 1, \\ y_2 = a_2 - a_1, \\ y_3 = b_2 - a_2, \\ y_4 = b_1 - b_2, \\ y_5 = 2 - b_1

Let us sum the variables:

y_1 + y_2 + ... + y_5 = 1, 0 \le y_i \le 1

This equation has solutions. In each of them, exactly one variable y_i equals , while all the others equal . Let us consider the correspondence between these solutions and the original sequences:

Algorithm implementation

Declare a constant and an array , where dp[n][k] = C_n^k.

#define MOD 1000000007
long long dp[3001][30];

The Cnk function computes the value of the binomial coefficient C_n^k.

long long Cnk(int n, int k)
{
  if (n == k) return 1;
  if (k == 0) return 1;
  if (dp[n][k] != -1) return dp[n][k];
  return dp[n][k] = (Cnk(n - 1, k - 1) + Cnk(n - 1, k)) % MOD;
}

The main part of the program. Read the input data.

scanf("%d %d", &n, &m);

Initialize the array.

memset(dp, -1, sizeof(dp));

Compute and print the answer C_{n+2m-1}^{2m}.

printf("%d\n", Cnk(n + 2 * m - 1, 2 * m));