跳到正文

题解

题解:B4380 [蓝桥杯青少年组省赛 2025] 魔术扑克牌排列

pengyirui约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月27日
篇幅
约 4 分钟
题目
B4380

版本

  1. v1当前

讲个笑话:考场高精度没打完。


卡特兰数板子题。

卡特兰数介绍

课前练习。
卡特兰数是组合数学中一种常出现于各种计数问题中的数列。
卡特兰数的定义为 Cn=1n−1(2nn)C_n=\frac{1}{n-1}\dbinom{2n}{n}。
其前几项为 1,1,2,5,14,42,132,429,1430,48621, 1, 2, 5, 14, 42, 132, 429, 1430, 4862。
卡特兰数的递推公式为 Cn=4n−2n+1Cn−1C_n=\dfrac{4n-2}{n+1}C_{n-1}。

关于本题

直接套用公式即可。

警告

高精度!!!
高精度!!!
高精度!!!

证明

我们可以把红牌看作 +1+1,蓝牌看作 −1-1。
题目要求转变为求前缀和均大于等于 0 的方案数。

总排列数

假设不考虑限制条件,那么总排列数为:

(2nn)\dbinom{2n}{n}

非法的排列数

我们可以把前 k 张牌中的 R 和 B 互换。( R 变 B,B 变 R。)
非法排列数为:

(2nn+1)\dbinom{2n}{n+1}

合法排列数

(2nn)−(2nn+1)=(2n)!n!n!−(2n)!(n+1)!(n−1)!=(2n)!n!n!(1−nn−1)=(2n)!n!n!⋅1n−1=1n−1(2nn)\dbinom{2n}{n}-\dbinom{2n}{n+1}\\=\frac{(2n)!}{n!n!}-\frac{(2n)!}{(n+1)!(n-1)!}\\=\frac{(2n)!}{n!n!}(1-\frac{n}{n-1})\\=\frac{(2n)!}{n!n!}\cdot\frac{1}{n-1}\\=\frac{1}{n-1}\dbinom{2n}{n}

不难发现,这就是卡特兰数的定义。

代码

以前搜集的高精度,码风不同,请勿在意。

C++
#include <bits/stdc++.h>
using namespace std;
long long n, a[1008617], c[1008617];
string f[105];
string div(string sa, int b) {
	int la = sa.length(), x = 0;
	for (int i = 0; i < la; i++) {
		a[i + 1] = sa[i] - '0';
	}
	for (int i = 1; i <= la; i++) {
		c[i] = (x * 10 + a[i]) / b;
		x = (x * 10 + a[i]) % b;
	}
	int lc = 1;
	while (c[lc] == 0 && lc < la) lc++;
	string s;
	for (int i = lc; i <= la; i++) {
		s += char(c[i] + '0');
	}
	return s;
}
string multiply(const string& num1, const string& num2) {
	string result(num1.size() + num2.size(), '0');
	int len1 = num1.size(), len2 = num2.size();
	for (int i = len1 - 1; i >= 0; --i) {
		int carry = 0;
		int n1 = num1[i] - '0';

		for (int j = len2 - 1; j >= 0; --j) {
			int sum = result[i + j + 1] - '0' + n1 * (num2[j] - '0') + carry;
			result[i + j + 1] = char(sum % 10 + '0');
			carry = sum / 10;
		}

		if (carry) {
			result[i] = char(carry + '0');
		}
	}
	size_t pos = result.find_first_not_of('0');
	return (pos == string::npos) ? "0" : result.substr(pos);
}
int main() {
	cin >> n;
	f[1] = "1";
	for (int i = 2; i <= n; i++) {
		string s = to_string(4 * i - 2);
		f[i] = div(multiply(f[i - 1], s), (i + 1));
	}
	cout << f[n];
	return 0;
}

课后练习

更大的数据
再推一下式子
还有逆元
更难的东西

原文