a850簡單

112 中投區複賽|三元字串計數問題

計算避免00、11的三元字串。

解題思路

令a,b,c分別為以0、1、2結尾的合法字串數,長度1時都是1。

新接0只能來自末位1或2,故a′=b+c;新接1同理b′=a+c;新接2無限制,c′=a+b+c。

按最後字元分類互斥且完整,每個合法新字串刪去末位也唯一對應上一層,因此遞推不重不漏。答案為a+b+c。

O(n)次大整數加法,O(n)位元儲存;n<50,C++使用任意精度整數避免64位元不足。 Python一次讀入另佔O(輸入文字長度)空間。

Step-by-step animation

示例:0、1、2皆合法。

回報動畫錯誤
步驟 1 / 3

長度1

0、1、2皆合法。

a1=1
b1=1
c1=1
總數
3

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
int main() {
    int n;
    cin >> n;
    cpp_int a = 1, b = 1, c = 1;
    for (int i = 1; i < n; i++) {
        cpp_int x = b + c, y = a + c, z = a + b + c;
        a = x;
        b = y;
        c = z;
    }
    cout << a + b + c << '\n';
}

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

更多