# Bit Manipulation# Simulation# Array

e797 - p4. 數位邏輯運算

🔗 前往 ZeroJudge 原題

題目描述

題目要求模擬數位邏輯閘 (AND, OR, XOR) 的運算。給定 N 個輸入訊號,在 T 個時間點的訊號值,計算每個時間點的 AND、OR 和 XOR 輸出。

解題思路

程式首先讀取輸入的 N 和 T。然後,讀取 N 行,每行包含 T 個 0 或 1 的訊號。對於每個時間點,程式計算 AND、OR 和 XOR 的輸出。AND 輸出為 1 當且僅當所有輸入都為 1,否則為 0。OR 輸出為 1 當且僅當至少有一個輸入為 1,否則為 0。XOR 輸出為 1 當且僅當有奇數個輸入為 1,否則為 0。程式將每個時間點的 AND、OR 和 XOR 輸出打印到標準輸出。

複雜度分析

  • 時間複雜度: O(N * T)
  • 空間複雜度: O(T)

程式碼

#include <iostream>
#include <string>
using namespace std;
int main(){
	cin.tie(0); ios::sync_with_stdio(false);
	int x,y;
	string a;
	cin >> x >> y;
	int xx=x;
	getline(cin,a);
	int ans[y]={0},al=(y-1)*2;
	while(x--){
		getline(cin,a);
		for(int i=0;i<=al;i+=2){
			ans[i/2]+=a[i]-48;
		}
	}
	cout << "AND:";
	for(int i=0;i<y;i++){
		if(ans[i]==xx)
		cout << " 1";
		else
		cout << " 0";
	}
	cout << "\nOR:";
	for(int i=0;i<y;i++){
		if(ans[i])
		cout << " 1";
		else
		cout << " 0";
	}
	cout << "\nXOR:";
	for(int i=0;i<y;i++){
		if(ans[i]%2)
		cout << " 1";
		else
		cout << " 0";
	}
}

Discussion