zoukankan      html  css  js  c++  java
  • BZOJ 4517: [Sdoi2016]排列计数 [容斥原理]

    4517: [Sdoi2016]排列计数

    题意:多组询问,n的全排列中恰好m个不是错排的有多少个


    容斥原理强行推♂倒她
    $恰好m个不是错排 $

    [ = ge m个不是错排 - ge m+1个不是错排inom{m+1}{m} - ge m+2个不是错排inom{m+2}{m}... \ = sum_{i=m}^n inom{n}{i} (n-i)!inom{i}{m} \ = frac{n!}{m!} sum_{i=m}^n (-1)^{i-m} frac{1}{(i-m)!} ]

    预处理阶乘逆元前缀和就可以(O(1))回答了
    其实错排公式也是这么推倒来的


    PS:发现题解全都是用的错排公式,~~等出一道你们不知道公式的题你们再用啊~~
    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #include <cmath>
    using namespace std;
    typedef long long ll;
    #define fir first
    #define sec second
    const int N=1e6+5, P=1e9+7;
    inline int read() {
    	char c=getchar(); int x=0, f=1;
    	while(c<'0' || c>'9') {if(c=='-')f=-1; c=getchar();}
    	while(c>='0' && c<='9') {x=x*10+c-'0'; c=getchar();}
    	return x*f;
    }
    
    int n, m;
    ll inv[N], fac[N], facInv[N], s[N];
    int main() {
    	freopen("permutation.in","r",stdin);
    	freopen("permutation.out","w",stdout);
    	inv[1]=1; fac[0]=facInv[0]=1;
    	s[0]=1;
    	for(int i=1; i<N; i++) {
    		if(i!=1) inv[i] = (P-P/i)*inv[P%i]%P;
    		fac[i] = fac[i-1]*i%P;
    		facInv[i] = facInv[i-1]*inv[i]%P;
    		s[i] = (s[i-1] + ((i&1) ? -facInv[i] : facInv[i]))%P;
    	}
    	int T=read();
    	while(T--) {
    		n=read(); m=read();  
    		ll ans = fac[n]*facInv[m]%P * s[n-m]%P; 
    		if(ans<0) ans+=P;
    		printf("%lld
    ", ans);
    	}
    }
    
    
  • 相关阅读:
    golang 相关
    ES root用户启动失败can not run elasticsearch as root
    基于 Flink CDC + Hudi 湖仓一体方案实践
    数据平台上云
    多云趋势
    数果实时数仓探索
    宽表的设计
    数仓指标体系
    Hudi在医疗大数据的应用
    Hudi on Flink上手使用总结
  • 原文地址:https://www.cnblogs.com/candy99/p/6652759.html
Copyright © 2011-2022 走看看