a502簡單雙重循環邊界與位元組狀態

CPE:Brainfuck (UVa 11956)

模擬100格環狀記憶體與0到255的環狀數值。

前往題目練習 →回報教學錯誤每筆時間 O(L+100),空間 O(100)。

解題思路

保存100個整數與指標p,初始都為0。>與<只改p,分別加1或加99後對100取模;+與−只改目前格,分別加1或加255後對256取模。這樣處理回繞時不會遇到C++負餘數。

點號對最終記憶體沒有影響,所以直接忽略,不印中間輸出。每個案例重新初始化,程式可能是空行,因此讀完T後以整行方式取得指令。最後依序印100個兩位大寫十六進位數,C++在下一個案例標號前切回十進位,避免標號也被印成十六進位。

Step-by-step animation

示意:-<+>

回報動畫錯誤
步驟 1 / 3

執行減號

第0格由0減1回繞為255。

格0=255
格99=0
p
0
指令序號
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
    int T;
    cin >> T;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    for (int tc = 1; tc <= T; ++tc) {
        string s;
        getline(cin, s);
        int memory[100] = {}, p = 0;
        for (char c : s) {
            if (c == '>')
                p = (p + 1) % 100;
            if (c == '<')
                p = (p + 99) % 100;
            if (c == '+')
                memory[p] = (memory[p] + 1) % 256;
            if (c == '-')
                memory[p] = (memory[p] + 255) % 256;
        }
        cout << dec << "Case " << tc << ':';
        for (int value : memory)
            cout << ' ' << uppercase << hex << setw(2) << setfill('0') << value;
        cout << '\n';
    }
}

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

更多