Files
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

119 lines
3.3 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

##[$AcWing$ $1316$. 有趣的数列](https://www.acwing.com/problem/content/description/1318/)
### 一、题目描述
我们称一个长度为 $2n$ 的数列是有趣的,当且仅当该数列满足以下三个条件:
- 它是从 $1$ 到 $2n$ 共 $2n$ 个整数的一个排列 ${a_i}$
- 所有的 **奇数项** 满足 $a_1<a_3<⋯<a_{2n−1}$,所有的 **偶数项** 满足 $a_2<a_4<⋯<a_{2n}$
- 任意相邻的两项 $a_{2i−1}$ 与 $a_{2i}$ $(1≤i≤n)$ 满足奇数项小于偶数项,即:$a_{2i−1}<a_{2i}$
任务是:对于给定的 $n$,请求出有多少个不同的长度为 $2n$ 的有趣的数列。
因为最后的答案可能很大,所以只要求输出答案 $mod$ $P$的值。
**输入格式**
只包含用空格隔开的两个整数 $n$ 和 $P$。
**输出格式**
仅含一个整数,表示不同的长度为 $2n$ 的有趣的数列个数 $mod$ $P$ 的值。
**数据范围**
$1≤n≤10^6,2≤P≤10^9$
**输入样例**
```cpp {.line-numbers}
3 10
```
**输出样例:**
```cpp {.line-numbers}
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\}$。
### 二、解题思路
**[嘉持老师的优秀教学视频](https://www.bilibili.com/video/BV1nE411A7ST)**
我们要有这种直觉:一旦发现输入是$3$,输出是$5$,很可能就是 **卡特兰数**。关于卡特兰数的讲解可以参考:**[网址](https://blog.csdn.net/weixin_42638946/article/details/115751984)**。
**如何判断某个问题是不是卡特兰数呢?一般由两种方式:**
- ① 能得到公式:$$\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$个节点,因为根点了一个节点。
- ② 能挖掘出如下性质:任意前缀中,某种东西的数量 ≥ 另一种东西数量。
![](https://dsideal.obs.cn-north-1.myhuaweicloud.com/HuangHai/BlogImages/202312041423367.png)
​
组合数等于三个阶乘相乘除,因此我们求出各个阶乘的质因数分解,就能得到组合数的模$p$后大小。
### 三、实现代码
```cpp {.line-numbers}
#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;
}
```