4517: [Sdoi2016]排列计数

4517: [Sdoi2016]排列计数

Time Limit: 60 Sec   Memory Limit: 128 MB
Submit: 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

Sample Output

0
1
20
578028887
60695423

HINT

Source

[ Submit][ Status][ Discuss]

要满足恰有m个位置A[i] == i,那么说明剩下n - m个位置A[i] != i,这不就是一个组合数和一个错排?
所以ans = C(n,m)*f[n-m]   f[i]:长度为i的错排方案
错排公式,,f[i] = (f[i-1] + f[i-2])*(i-1)
#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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值