b349中等

107 臺北市資訊學科能力競賽決賽(2018)|配對連線

計算圓周上不交叉的完美配對數。

解題思路

計算圓周上不交叉的完美配對數。

固定第一點的配對,它把圓分成各有偶數點的兩側;兩側必各自不交叉,且選擇互相獨立。

因此C[n]=sum C[k]C[n−1−k],C[0]=1,為Catalan數。可用等價閉式C[n]=binom(2n,n)/(n+1)的連續比值精確計算。

C[i+1]=C[i]×2(2i+1)/(i+2),每一步都整除;任意精度保存完整答案。

每筆 O(n)次大整數乘除,額外空間為答案位數;Python讀取O(q),實際成本另計整數位數。

Step-by-step animation

Catalan數C0至C3的分解示例

回報動畫錯誤
步驟 1 / 3

步驟 1

C0=1,空問題有唯一方式。

C0=1
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
int main() {
    int n;
    while (cin >> n) {
        if (n == 0)
            break;
        cpp_int c = 1;
        for (int i = 0; i < n; i++)
            c = c * 2 * (2 * i + 1) / (i + 2);
        cout << c << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多