C. 排列计数(错排)

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

Input
第一行一个数 T,表示有 T 组数据。
接下来 T 行,每行两个整数 n,m。
T=500000,n≤1000000,m≤1000000
Output
输出T行,每行一个数,表示求出的序列数

Samples
Input 复制
5
1 0
1 1
5 2
100 50
10000 5000
Output
0
1
20
578028887
60695423

题解: 这个题好想的就是,一共n个数,找出m个数固定,有 C n m C_{n}^{m} Cnm种,然后剩下 n − m n-m nm个错排。这个 C n m C_{n}^{m} Cnm好整就是就用阶乘和其逆元来求。难点就是 n − m n-m nm错排。我们用容斥定理来求是肯定会T的1e6的数据,所以需要换种思路来想:
公式:
c u o [ i ] = ( i − 1 ) ∗ ( c u o [ i − 1 ] + c u o [ i − 2 ] ) cuo[i]=(i-1)*(cuo[i-1]+cuo[i-2]) cuo[i]=(i1)(cuo[i1]+cuo[i2])
假设当前考虑新加入第i个数,如果与k互换 那么方案为cuo[i-2],(就是加入一个数,就是除了加入那一个和k这个互换其他错排,也就是cuo[i-2])
如果不是则为cuo[i-1],(如果不是两个互换就是cuo[i-1],一个数固定(原本有的),剩下的(i-1)个数错排)
这样的k有(i-1)个
注意 f[0]=1,f[1]=0,f[2]=1;
代码放着了

#include <map>
#include <queue>
#include <string>
#include<iostream>
#include<stdio.h>
#include<string.h>
#include <algorithm>
#include <math.h>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
typedef pair<ll,ll> pii;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define mem(a,x) memset(a,x,sizeof(a))
#define debug(x) cout << #x << ": " << x << endl;
#define rep(i,n) for(int i=0;i<(n);++i)
#define repi(i,a,b) for(int i=int(a);i<=(b);++i)
#define repr(i,b,a) for(int i=int(b);i>=(a);--i)
const int maxn=1e6+10;
#define inf 0x3f3f3f3f
#define sf scanf
#define pf printf
const int mod=1e9+7;
const int MOD=1e9+7;

inline int read() {
    int x=0;
    bool t=false;
    char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    if(ch=='-')t=true,ch=getchar();
    while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
    return t?-x:x;
}

vector<ll> m1;
vector<ll> m2;
priority_queue<ll, vector<ll>, greater<ll> > mn;  //上  小根堆 		小到大
priority_queue<ll, vector<ll>, less<ll> > mx;  //下   	大根堆  	大到小
map<ll,ll>mp;
ll n,m,p;
ll fac[maxn];
ll infac[maxn];
ll cuo[maxn];
ll qpow(ll a,ll b){
    ll ans=1;
    while(b){
        if(b&1) ans=ans*a%mod;
        b>>=1;
        a=a*a%mod;
    }
    return ans;
}
int main() {
    ll t;
    cin>>t;
    fac[0]=1;
    fac[1]=1;
    for(int i=2;i<=1000000;i++){
        fac[i]=fac[i-1]*i%mod;
    }
    infac[0]=1;
    infac[1000000]=qpow(fac[1000000],mod-2);
    for(int i=999999;i>0;i--){
        infac[i]=infac[i+1]*(i+1)%mod;
    }
    cuo[0]=1;cuo[1]=0;cuo[2]=1;
    for(int i=3;i<=1000000;i++){
        cuo[i]=((i-1)*((cuo[i-1]+cuo[i-2])%mod))%mod;
    }

    while(t--){
        scanf("%lld%lld",&n,&m);
       ll ans=fac[n]*infac[m]%mod*infac[n-m]%mod*cuo[n-m]%mod;
        printf("%lld\n",ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值