uva11481 - Arrange the Numbers N个数前M个错排

Consider this sequence {1, 2, 3, … , N}, as a initial sequence of firstN natural numbers. You can rearrange this sequence in many ways. Therewill beN! different arrangements. You have to calculate the number ofarrangement of firstN natural numbers, where in first M (M<=N)positions, exactlyK (K<=M) numbers are in its initial position.

 

Example:

 

For, N = 5, M = 3, K =2

 

You should count this arrangement {1, 4, 3, 2, 5}, here in first 3positions 1 is in 1st position and 3 in 3rd position. Soexactly 2 of its first 3 are in there initial position.

 

But you should not count this {1, 2, 3, 4, 5}.

 

Input

The first line ofinput is an integer T(T<=1000) that indicates the number of testcases. Next T line contains 3 integers each,N(1<=N<=1000), M,and K.

 

Output

For each case,output the case number, followed by the answer modulo 1000000007. Lookat the sample for clarification.

 

SampleInput                             Outputfor Sample Input

1
5 3 2

Case 1: 12

 

  N个数,前M个里有K个在原位上。

  先从M个里选K个,剩下的问题就是n个数里前m个错排的问题了。

  设dp[i][j]为前i个数错排,后j个数任意的排列个数,在dp[i][j-1]的情况下,第j个数可以放在最后或者和前面任何一个交换,这样就有(i+j)*dp[i][j-1]种,若前i个数只有i-1个错排,有1个还在原位,那么第i个数和这个数交换也满足,由于在原位的数可以是第1-i位,这样有i*dp[i-1][j-1]种。

   临界条件dp[i][0]为i位数的错排,dp[0][i]为i!

#include
#include
#include
#include
#include
#include
#include
#include
#include
#define eps 1e-9
#define MAXN 1010
#define MOD 1000000007
using namespace std;
int T,N,M,K;
long long dp[MAXN][MAXN],C[MAXN][MAXN];
void init(){
    memset(C,0,sizeof(C));
    memset(dp,0,sizeof(dp));
    C[0][0]=1;
    for(int i=1;i



你可能感兴趣的:(DP)