题解:B4380 [蓝桥杯青少年组省赛 2025] 魔术扑克牌排列
讲个笑话:考场高精度没打完。
卡特兰数板子题。
卡特兰数介绍
课前练习。\
卡特兰数是组合数学中一种常出现于各种计数问题中的数列。\
卡特兰数的定义为
关于本题
直接套用公式即可。
:::warning[警告] 高精度!!!\ 高精度!!!\ 高精度!!! :::
证明
我们可以把红牌看作
总排列数
假设不考虑限制条件,那么总排列数为:
非法的排列数
我们可以把前 k 张牌中的 R 和 B 互换。( R 变 B,B 变 R。)\ 非法排列数为:
合法排列数
不难发现,这就是卡特兰数的定义。
代码
以前搜集的高精度,码风不同,请勿在意。
#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;
}
课后练习
更大的数据\ 再推一下式子\ 还有逆元\ 更难的东西