You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3.3 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

##AcWing 1316. 有趣的数列

一、题目描述

我们称一个长度为 2n 的数列是有趣的,当且仅当该数列满足以下三个条件:

  • 它是从 12n2n 个整数的一个排列 {a_i}

  • 所有的 奇数项 满足 a_1<a_3<⋯<a_{2n1},所有的 偶数项 满足 a_2<a_4<⋯<a_{2n}

  • 任意相邻的两项 a_{2i1}a_{2i} (1≤i≤n) 满足奇数项小于偶数项,即:a_{2i1}<a_{2i}

任务是:对于给定的 n,请求出有多少个不同的长度为 2n 的有趣的数列。

因为最后的答案可能很大,所以只要求输出答案 mod P的值。

输入格式

只包含用空格隔开的两个整数 nP

输出格式

仅含一个整数,表示不同的长度为 2n 的有趣的数列个数 mod P 的值。

数据范围

1≤n≤10^6,2≤P≤10^9

输入样例

3 10

输出样例:

5

样例解释

对应的 5 个有趣的数列分别为 \{1,2,3,4,5,6\},\{1,2,3,5,4,6\},\{1,3,2,4,5,6\},\{1,3,2,5,4,6\},\{1,4,2,5,3,6\}

二、解题思路

嘉持老师的优秀教学视频

我们要有这种直觉:一旦发现输入是3,输出是5,很可能就是 卡特兰数。关于卡特兰数的讲解可以参考:网址

如何判断某个问题是不是卡特兰数呢?一般由两种方式:

  • ① 能得到公式:\large f(n)=f(0) \times f(n-1) + f(1) \times f(n-2) + ... +f(n-1)\times f(0)

解释:联想一下嘉持老师的画二叉树,就是向左子树分配i个节点,那么向右子树就分配n-i-1个节点,因为根点了一个节点。

  • ② 能挖掘出如下性质:任意前缀中,某种东西的数量 ≥ 另一种东西数量。

组合数等于三个阶乘相乘除,因此我们求出各个阶乘的质因数分解,就能得到组合数的模p后大小。

三、实现代码

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
const int N = 2000010;

int n, mod;
int primes[N], cnt;
bool st[N];

void get_primes(int n) {
    for (int i = 2; i <= n; i++) {
        if (!st[i]) primes[cnt++] = i;
        for (int j = 0; primes[j] * i <= n; j++) {
            st[i * primes[j]] = true;
            if (i % primes[j] == 0) break;
        }
    }
}

int qmi(int a, int k) {
    int res = 1;
    while (k) {
        if (k & 1) res = res * a % mod;
        a = a * a % mod;
        k >>= 1;
    }
    return res;
}

int get(int n, int p) {
    int s = 0;
    while (n) {
        s += n / p;
        n /= p;
    }
    return s;
}

int C(int a, int b) {
    int res = 1;
    for (int i = 0; i < cnt; i++) {
        int p = primes[i];
        int s = get(a, p) - get(b, p) - get(a - b, p);
        res = res * qmi(p, s) % mod;
    }
    return res;
}

signed main() {
    cin >> n >> mod;
    get_primes(n * 2);
    cout << (C(n * 2, n) - C(n * 2, n - 1) + mod) % mod << endl;
}