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<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<algorithm>
#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<MAXN;i++){
        C[i][0]=C[i][i]=1;
        for(int j=1;j<i;j++) C[i][j]=(C[i-1][j]+C[i-1][j-1])%MOD;
    }
    dp[2][0]=1;
    for(int i=3;i<MAXN;i++) dp[i][0]=(i-1)*(dp[i-1][0]+dp[i-2][0])%MOD;
    dp[0][0]=1;
    for(int i=1;i<MAXN;i++) dp[0][i]=i*dp[0][i-1]%MOD;
    for(int i=1;i<MAXN;i++)
        for(int j=1;j<MAXN;j++) dp[i][j]=((i+j)*dp[i][j-1]%MOD+i*dp[i-1][j-1]%MOD)%MOD;
}
int main(){
    freopen("in.txt","r",stdin);
    init();
    int cas=0;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d%d",&N,&M,&K);
        printf("Case %d: %lld\n",++cas,C[M][K]*dp[M-K][N-M]%MOD);
    }
    return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值