数学(错排):BZOJ 4517: [Sdoi2016]排列计数

4517: [Sdoi2016]排列计数

Time Limit: 60 Sec  Memory Limit: 128 MB
Submit: 693  Solved: 434
[Submit][Status][Discuss]

Description

求有多少种长度为 n 的序列 A,满足以下条件:
1 ~ n 这 n 个数在序列中各出现了一次
若第 i 个数 A[i] 的值为 i,则称 i 是稳定的。序列恰好有 m 个数是稳定的
满足条件的序列可能很多,序列数对 10^9+7 取模。

Input

第一行一个数 T,表示有 T 组数据。
接下来 T 行,每行两个整数 n、m。
T=500000,n≤1000000,m≤1000000

Output

输出 T 行,每行一个数,表示求出的序列数

Sample Input

5
1 0
1 1
5 2
100 50
10000 5000

Sample Output

0
1
20
578028887
60695423
  
  错排还是很简单的……
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 const int maxn=1000010;
 6 const long long mod=1000000007LL;
 7 long long f[maxn],fac[maxn];
 8 long long Inv(int x){
 9     return x==1?1:(mod-mod/x)*Inv(mod%x)%mod;
10 }
11 
12 int main(){
13 #ifndef ONLINE_JUDGE
14     freopen("permutation.in","r",stdin);
15     freopen("permutation.out","w",stdout);
16 #endif
17     fac[0]=1;f[0]=1;f[1]=0;
18     for(int i=1;i<=1000000;i++)fac[i]=fac[i-1]*i%mod;
19     for(int i=2;i<=1000000;i++)f[i]=(i-1)*(f[i-1]+f[i-2])%mod;
20     
21     int T,n,m;
22     scanf("%d",&T);
23     while(T--){
24         scanf("%d%d",&n,&m);
25         printf("%d\n",f[n-m]*fac[n]%mod*Inv(fac[m])%mod*Inv(fac[n-m])%mod);
26     }
27     return 0;
28 }

 

posted @ 2016-06-12 19:24  TenderRun  阅读(197)  评论(0编辑  收藏  举报