b341中等

94 臺北市資訊學科能力競賽(2005)|組合電路的模擬

回答正向電路輸出及指定輸出的輸入數。

解題思路

回答正向電路輸出及指定輸出的輸入數。

NAND(x,y)=1−xy,先計算四個相鄰輸入中間閘Bi,再以相鄰Bi計算三個輸出Fi。

對五位查詢直接代入;對三位輸出查詢,枚舉全部2^5=32種輸入,統計計算結果相等者。

每種輸入被枚舉恰一次,固定電路為確定函數,所以統計就是全部可能輸入數。

預處理 O(32),每筆查詢 O(1)。C++額外空間 O(1);Python一次split保留q個查詢,空間 O(q)。

Step-by-step animation

固定 NAND 電路全輸入枚舉逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

輸入11111,四個中間NAND都是0。

B=0000
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
string calc(string s) {
    string b, f;
    for (int i = 0; i < 4; i++)
        b += char('0' + 1 - (s[i] - '0') * (s[i + 1] - '0'));
    for (int i = 0; i < 3; i++)
        f += char('0' + 1 - (b[i] - '0') * (b[i + 1] - '0'));
    return f;
}
int main() {
    map<string, int> count;
    for (int k = 0; k < 32; k++) {
        string s;
        for (int j = 4; j >= 0; j--)
            s += char('0' + ((k >> j) & 1));
        count[calc(s)]++;
    }
    string s;
    while (cin >> s)
        if (s.size() == 5)
            cout << calc(s) << '\n';
        else
            cout << count[s] << '\n';
}

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

更多