문제 : https://www.acmicpc.net/problem/6568
문제 요약 : 프로그램 종료 후 가산기의 값 출력
C++
소스코드 : https://github.com/cbkpar/BOJ/blob/main/boj_6568.cpp
채점 번호 | 아이디 | 문제 번호 | 결과 | 메모리 | 시간 | 언어 | 코드 길이 |
57976757 | cbkpar | 6568 | 맞았습니다!! | 2024KB | 0ms | C++17 | 1279B |
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int Fetch(string str)
{
int iSum = 0;
for (char ch : str)
{
iSum <<= 1;
iSum += ch - '0';
}
return iSum;
}
void Decode(const int command, int& _operator, int& _operand)
{
_operator = command >> 5;
_operand = command % 32;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
vector<int> vecMemory(32, 0);
int iIndex = 0;
string strCommand;
while (cin >> strCommand)
{
vecMemory[iIndex] = Fetch(strCommand);
iIndex = (iIndex + 1) % 32;
if (iIndex == 0)
{
int iPC = 0;
int iSum = 0;
while (iPC >= 0)
{
int iTempPC = iPC;
int iOperator, iOperand;
Decode(vecMemory[iPC], iOperator, iOperand);
iPC = (iPC + 1) % 32;
switch (iOperator)
{
case 0: vecMemory[iOperand] = iSum; break;
case 1: iSum = vecMemory[iOperand]; break;
case 2: iPC = (iSum == 0 ? iOperand : iPC); break;
case 3: break;
case 4: if (--iSum < 0) iSum += 256; break;
case 5: iSum = (++iSum) % 256; break;
case 6: iPC = iOperand; break;
case 7: iPC = -1; break;
}
}
for (int i = 7; i >= 0; --i)
{
cout << ((iSum & (1 << i)) == (1 << i) ? "1" : "0");
}
cout << "\n";
}
}
return 0;
}
시스템 프로그래밍 공부에 좋은 문제인 것 같아서 풀어 보았다.
우선 받은 명령어를 RAM 에 적재하듯이 올려준다. (Load)
RAM과 CPU에서는 크게 Fetch - Decode - Execute 가 일어나게 된다.
이를 기반으로 알고리즘을 작성하면 된다.
1. 해당 PC가 가리키는 명령어를 operator와 operand로 분리한다.
2. 명령어 해석후에 PC레지스터 의 값을 1 증가시키며 이때 32보다 커지면 0으로 만들어 준다.
3. operator에 따른 명령을 수행한다.
이 문제에서 눈여겨 볼 점은 명령을 통해 직접 계산을 하였을 경우
총 5비트밖에 사용하지 못하기 때문에 32가 넘어가는 숫자에 대한 연산을 할 수 없지만
값의 주소를 이용해 연산 횟수는 늘지만 8비트 모두 연산에 사용할 수 있다.
이 방법은 Indirect 모드라고 볼 수 있다.
'백준온라인' 카테고리의 다른 글
[백준온라인] 27468번 2배 또는 0.5배 (0) | 2023.09.21 |
---|---|
[백준온라인] 27516번 과녁 맞추기 (0) | 2023.03.01 |
[백준온라인] 12933번 오리 (0) | 2021.10.13 |
[백준온라인] 2687번 팩스 받기 (0) | 2021.10.13 |
[백준온라인] 2686번 팩스 (0) | 2021.10.13 |