熱門文章

2026年1月1日 星期四

ZeroJudge 解題筆記:a467. 11398 - The Base-1 Number System

作者:王一哲
日期:2026年1月1日


ZeroJudge 題目連結:a467. 11398 - The Base-1 Number System

解題想法


依照題目敘述處理讀取到的字串,如果字串內容只有 ~ 就中止程式; 如果是其它內容,將字串用空格分隔後存入串列 arr 之中。可以用字串或是串列儲存一行測資轉換後得到的 0, 1 字串 result。依序讀取 arr 的內容存入 a,如果 a 是 # 將 result 用 2 進位制轉換成整數後輸出;如果 a 是 0,將 flag 改成 1; 如果 a 是 1,將 flag 改成 0;其它狀況,在 result 後面接上 a 的長度減 2 個 flag。

Python 程式碼


使用時間約為 25 ms,記憶體約為 3 MB,通過測試。
import sys

result = ""
flag = "1"
for line in sys.stdin:
    if line.strip() == "~": break
    arr = line.split()
    for a in arr:
        if a == "#":
            print(int(result, 2))
            result = ""
        elif a == "0": flag = "1"
        elif a == "00": flag = "0"
        else:
            result += flag*(len(a)-2)

使用時間約為 84 ms,記憶體約為 4.4 MB,通過測試。
import sys

result = []
lines = sys.stdin.readlines()
flag = "1"
idx = 0
while idx < len(lines):
    if lines[idx].strip() == "~": break
    arr = lines[idx].split()
    idx += 1
    res = []  # 暫存這行測資輸出結果用的串列
    for a in arr:
        if a == "#":
            num = int("".join(res), 2)
            res.clear()
            result.append(f"{num:d}\n")
        elif a == "0": flag = "1"
        elif a == "00": flag = "0"
        else:
            res += [flag]*(len(a)-2)
sys.stdout.write("".join(result))


C++ 程式碼


使用時間約為 6 ms,記憶體約為 324 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;

int bin(string s) {
    int n = 0, b = 1;
    for(auto it = s.crbegin(); it != s.crend(); it++) {
        if ((*it) == '1') n += b;
        b <<= 1;
    }
    return n;
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string result = "", s;
    char flag = '1';
    while(cin >> s && s != "~") {
        if (s == "#") {
            cout << bin(result) << "\n";
            result.clear();
        } else if (s == "0") {
            flag = '1';
        } else if (s == "00") {
            flag = '0';
        } else {
            size_t n = s.size();
            string t (n-2, flag);
            result += t;
        }
    }
    return 0;
}


沒有留言:

張貼留言