4517: [Sdoi2016]排列计数
Time Limit: 60 Sec Memory Limit: 128 MBSubmit: 907 Solved: 563
[ 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
1 0
1 1
5 2
100 50
10000 5000
Sample Output
0
1
20
578028887
60695423
1
20
578028887
60695423
HINT
Source
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<bitset>
#include<ext/pb_ds/priority_queue.hpp>
using namespace std;
const int maxn = 1E6 + 10;
const int N = 1000000;
typedef long long LL;
const LL mo = 1000000007;
int T,f[maxn],fac[maxn],inv[maxn];
int Add(const LL &x,const LL &y) {return (x + y) % mo;}
int Mul(const LL &x,const LL &y) {return x*y%mo;}
int ksm(int x,int y)
{
int ret = 1;
for (; y; y >>= 1)
{
if (y&1) ret = Mul(ret,x);
x = Mul(x,x);
}
return ret;
}
int C(int n,int m)
{
int Inv = Mul(inv[m],inv[n-m]);
return Mul(fac[n],Inv);
}
int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif
f[0] = 1; f[1] = 0; f[2] = 1; fac[0] = 1; cin >> T;
for (int i = 3; i <= N; i++) f[i] = Mul(Add(f[i-1],f[i-2]),i-1);
for (int i = 1; i <= N; i++) fac[i] = Mul(fac[i-1],i);
inv[N] = ksm(fac[N],mo-2);
for (int i = N-1; i >= 0; i--) inv[i] = Mul(inv[i+1],i+1);
while (T--)
{
int n,m; scanf("%d%d",&n,&m);
if (m > n) puts("0");
else printf("%d\n",Mul(C(n,m),f[n-m]));
}
return 0;
}