码迷,mamicode.com
首页 > 其他好文 > 详细

[SDOI 2016]排列计数

时间:2018-02-14 23:57:55      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:main   void   line   gpo   sdoi   char   pre   get   bool   

Description

题库链接

求有多少种长度为 \(n\) 的序列 \(A\) ,满足以下条件:

  1. \(1 \sim n\)\(n\) 个数在序列中各出现了一次

  2. 若第 \(i\) 个数 \(A[i]\) 的值为 \(i\) ,则称 \(i\) 是稳定的。序列恰好有 \(m\) 个数是稳定的

满足条件的序列可能很多,序列数对 \(10^9+7\) 取模。

\(T\leq 500000\)\(n\leq 1000000\)\(m\leq 1000000\)

Solution

需要用到组合数学和错排公式。

\(ans=C_n^m\cdot D_{n-m}\)

其中 \(D_n=n!\left(1-\frac{1}{1!}+\frac{1}{2!}-\frac{1}{3!}+\cdots+(-1)^n\frac{1}{n!}\right)\)

Code

//It is made by Awson on 2018.2.14
#include <bits/stdc++.h>
#define LL long long
#define dob complex<double>
#define Abs(a) ((a) < 0 ? (-(a)) : (a))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Swap(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))
#define writeln(x) (write(x), putchar('\n'))
#define lowbit(x) ((x)&(-(x)))
using namespace std;
const int N = 1000000;
const int MOD = 1e9+7;
void read(int &x) {
    char ch; bool flag = 0;
    for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar());
    for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar());
    x *= 1-2*flag;
}
void print(int x) {if (x > 9) print(x/10); putchar(x%10+48); }
void write(int x) {if (x < 0) putchar('-'); print(Abs(x)); }

int A[N+5], inv[N+5], D[N+5], n, m, t;

void work() {
    inv[0] = inv[1] = A[1] = A[0] = D[0] = 1;
    for (int i = 2; i <= N; i++) inv[i] = -1ll*(MOD/i)*inv[MOD%i]%MOD;
    for (int i = 2; i <= N; i++) A[i] = 1ll*A[i-1]*i%MOD, inv[i] = 1ll*inv[i]*inv[i-1]%MOD;
    for (int i = 1; i <= N; i++)
        if (i%2 == 1) D[i] = (D[i-1]-inv[i])%MOD;
        else D[i] = (D[i-1]+inv[i])%MOD;
    for (int i = 0; i <= N; i++) D[i] = 1ll*D[i]*A[i]%MOD;
    read(t);
    while (t--) {
        read(n), read(m);
        if (n < m) puts("0");
        else writeln(int((1ll*A[n]*inv[m]%MOD*inv[n-m]%MOD*D[n-m]%MOD+MOD)%MOD));
    }
}
int main() {
    work(); return 0;
}

[SDOI 2016]排列计数

标签:main   void   line   gpo   sdoi   char   pre   get   bool   

原文地址:https://www.cnblogs.com/NaVi-Awson/p/8449108.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!