Bzoj 4517: [Sdoi2016]排列计数(排列组合)

来源:互联网 发布:jsp解析json字符串 编辑:程序博客网 时间:2024/04/30 01:19

4517: [Sdoi2016]排列计数
Time Limit: 60 Sec Memory Limit: 128 MB
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
鸣谢Menci上传

/*做法和题目一样.简单的组合数学题.答案=C(n,m)*F[n-m].F[i]表示i个数的错排个数.如果忘了公式可以用容斥原理推一发....*/#include<iostream>#include<cstdio>#define MAXN 1000001#define LL long long#define mod 1000000007using namespace std;LL n,m,ans,f[MAXN],M[MAXN];int read(){    int x=0,f=1;char ch=getchar();    while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}    while(ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();    return x*f;}void pre(){    f[0]=1,f[1]=0,f[2]=1;    for(int i=3;i<=MAXN-1;i++) f[i]=(i-1)*(f[i-1]+f[i-2])%mod;    M[0]=1;    for(int i=1;i<=MAXN-1;i++) M[i]=M[i-1]*i%mod; }LL mi(LL a,int b){    LL tot=1;    while(b)    {        if(b&1) tot=tot*a%mod;        a=a*a%mod;        b>>=1;    }    return tot;}void slove(){    ans=M[n]*mi(M[m],mod-2)%mod*mi(M[n-m],mod-2)%mod*f[n-m]%mod;    printf("%lld\n",ans);}int main(){    int t;    t=read();pre();    while(t--)    {        n=read(),m=read();        slove();    }    return 0;}
0 0
原创粉丝点击