数学总结——卡特兰数

· · 算法·理论

卡特兰数最重要的是它的折线对称映射思路

定义与运算

卡特兰数 C_n 表示在一个坐标系中,起点在 (0,0),终点 (n,n),可以向左走或向上走,不能走到 y=x 对角线上方的路径数。

公式1:C_n = \sum_{i=0}^{n-1} C_iC_{n-i-1}

枚举最后一次碰到对角线的点 (i,i),从 (0,0) 到 (i,i) 的方案数为 C_i;从(i,i) 到 (n,n) 不碰到对角线的方案数,显然等价于把起点向右移动一格、终点向下移动一格的路径数,即 C_{n-i-1}

公式2:C_n = \binom{2n}{n}-\binom{2n}{n+1}

不超过一条线不好处理,考虑把对角线向上移动一格变成 y=x+1,不超过 y=x 变成不碰到 y=x+1。这个合法情况也是不好处理的,考虑正难则反,总路径数为 \binom{2n}{n},统计非法路径。

考虑对所有非法路径进行以下映射:把在 (0,0) 到第一次碰到 y=x+1 线的点 (k,k+1) 全部沿着对角线翻折。翻折完成后,还是一条路径,但是起点变成了 (-1,1),如图:

这样映射有如下性质:

所以,(-1,1) 到 (n,n) 的路径和 (0,0) 到 (n,n) 的非法路径可以一一对应,所以非法路径的数量是 \binom{2n}{n+1},合法路径数量即为 \binom{2n}{n}-\binom{2n}{n+1}

公式3:C_n=\frac{4n-2}{n+1}C_{n-1}

与公式2等价,把组合数展开融在一起就是该公式。

基本运用

T1 [AHOI2012] 树屋阶梯

计数题不给模数是有什么心事吗?

思路

令 T_i 表示 n=i 的答案。

$$ T_i=\sum_{j=0}^{n-1}T_jT_{i-j-1} $$ 与卡特兰数计算公式1相同,就是卡特兰数。 ### 代码 ~~论神秘压位高精度~~ ```cpp #include <bits/stdc++.h> using namespace std; /* 高精度略 */ const int N = 505; int n; BigInteger catalan[N]; signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; catalan[0] = 1; for(int i = 1;i <= n;i++) for(int j = 0;j <= i-1;j++) catalan[i] += catalan[j]*catalan[i-j-1]; cout << catalan[n]; return 0; } ``` # T2 [[SCOI2010] 生成字符串](https://www.luogu.com.cn/problem/P1641) ### 思路 增量构造,初始在 $(0,0)$ 加入一格 $1$ 看作向右走一格,加入一格 $0$ 看作向上走一格,不能超过 $y=x$ 这条对角线,终点是 $(n,m)$。可以用卡特兰数同理的折线翻折,得出结果为 $\binom{n+m}{n}-\binom{m+m}{n+1}$。 ### 代码 ```cpp #include <bits/stdc++.h> using namespace std; #define int long long const int mod = 20100403,N = 2e6+5; int n,m,fact[N]; int power(int a,int b) { int the_ans = 1; while(b) { if(b&1) the_ans = the_ans*a%mod; a = a*a%mod; b >>= 1; } return the_ans; } int c(int n,int m) { if(n < m || m < 0) return 0; return fact[n]*power(fact[n-m]*fact[m]%mod,mod-2)%mod; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; fact[0] = 1; for(int i = 1;i <= n+m;i++) fact[i] = fact[i-1]*i%mod; cout << (c(n+m,n)-c(n+m,n+1)+mod)%mod; return 0; } ``` # T3 [Natasha, Sasha and the Prefix Sums](https://www.luogu.com.cn/problem/CF1204E) ### 思路 枚举最大前缀和 $\text{maxpre}$,统计每次碰到 $y=x+\text{maxpre}$ 线的个数。我们可以计算出最大值大于等于某个值的方案数 $\text{ans}_i$,可以容斥解决,但也可以直接计算 $$ \sum ans_i $$ 为什么是对的?最大值是多少就会被算多少次。 ### 代码 ```cpp #include <bits/stdc++.h> using namespace std; #define int long long const int mod = 998244853,N = 8005; int n,m,fact[N],ans = 0; int power(int a,int b) { int the_ans = 1; while(b) { if(b&1) the_ans = the_ans*a%mod; a = a*a%mod; b >>= 1; } return the_ans; } int c(int n,int m) { if(n < m || m < 0) return 0; return fact[n]*power(fact[n-m]*fact[m]%mod,mod-2)%mod; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; fact[0] = 1;for(int i = 1;i <= n+m+2;i++) fact[i] = fact[i-1]*i%mod; for(int maxpre = 1;maxpre <= n;maxpre++) { if(n-m >= maxpre) ans = (ans+c(n+m,n))%mod; else if(n-m < maxpre) ans = (ans+c(n+m,n-maxpre))%mod; } cout << ans; return 0; } ```