KiAsaGibona's blog

By KiAsaGibona, 11 years ago, In English

Hi.

This is a Link of a Dynamic programming problem which was published in 2010 Asia Regional Harbin .

I am seeking some help finding the idea to attack this kind of problems. Any kind of suggestion or advice will be a great hand. You can also provide some problems of same category for future references.

The problem statement is given below.

Have a nice day :) .

Problem Description

Given a permutation a1, a2, … aN of {1, 2, …, N}, we define its E-value as the amount of elements where ai > i. For example, the E-value of permutation {1, 3, 2, 4} is 1, while the E-value of {4, 3, 2, 1} is 2. You are requested to find how many permutations of {1, 2, …, N} whose E-value is exactly k.

Input

There are several test cases, and one line for each case, which contains two integers, N and k. (1 <= N <= 1000, 0 <= k <= N).

Output

Output one line for each case. For the answer may be quite huge, you need to output the answer module 1,000,000,007.

Sample Input

3 0

3 1

Sample Output

1

4

Hint There is only one permutation with E-value 0: {1,2,3}, and there are four permutations with E-value 1: {1,3,2}, {2,1,3}, {3,1,2}, {3,2,1}

Source

2010 Asia Regional Harbin

  • Vote: I like it
  • +5
  • Vote: I do not like it

»
11 years ago, # |
Rev. 6   Vote: I like it +8 Vote: I do not like it

I just got Accepted, using following formula:

f[n][k] = f[n-1][k] + f[n-1][k]*k + f[n-1][k-1]*(n-k);

where n is number of element and k is required E-value.

Explain: We consider three different ways to construct answer of (N,K) from answer of (N-1,K) and (N-1,K-1).

  1. From (N-1,K) : put the element value N in N-th position. Obviously, we now have (N-1,K) sequence.

  2. From (N-1,K) : swap position of N-th element (value is N) with a position X where a[X] > X, we now have a new sequence with E-value is K. Because the initial sequence has K position like that, we now have f[N-1][K]*K new sequence.

  3. From (N-1,K-1) : swap position of N-th element (value is N) with a position X where a[X] <= X, we now also have a new sequence with E-value = K. Initially, we have (N-1)-(K-1) = N — K position like that, we now have f[N-1][K-1]*(N-K) new sequence.

Adding some necessary Mod operators, you will get the proper formula.