프로그래밍/알고리즘

BOJ 16506 · CPU

반응형


알고리즘 분류 : 시뮬레이션, 문자열 처리  


어셈블리어 코드를 기계어로 코드로 번역하여 출력하는 문제다. 문제를 천천히 정독하여 그대로 구현하면 된다. 문자열 처리는 파이썬이 간결하고 구현하기 쉽다.




C++ 소스코드


#include <iostream>
#include <string>
using namespace std;

const string reg[] = {"000", "001", "010", "011", "100", "101", "110", "111"};
const string con[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
                      "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};

bool opcode(string &op) {
    if (!op.compare(0, 3, "ADD", 3)) cout << "0000";
    else if (!op.compare(0, 3, "SUB", 3)) cout << "0001";
    else if (!op.compare(0, 3, "MOV", 3)) cout << "0010";
    else if (!op.compare(0, 3, "AND", 3)) cout << "0011";
    else if (!op.compare(0, 2, "OR", 2)) cout << "0100";
    else if (!op.compare(0, 3, "NOT", 3)) cout << "0101";
    else if (!op.compare(0, 4, "MULT", 4)) cout << "0110";
    else if (!op.compare(0, 5, "LSFTL", 5)) cout << "0111";
    else if (!op.compare(0, 5, "LSFTR", 5)) cout << "1000";
    else if (!op.compare(0, 5, "ASFTR", 5)) cout << "1001";
    else if (!op.compare(0, 2, "RL", 2)) cout << "1010";
    else if (!op.compare(0, 2, "RR", 2)) cout << "1011";
    if (op[(int)op.size()-1] == 'C') {
        cout << "10";
        return true;
    } else {
        cout << "00";
        return false;
    }
}

void solve() {
    string OP;
    int D, A, B;
    cin >> OP >> D >> A >> B;
    if (opcode(OP)) cout << reg[D] << reg[A] << con[B] << '\n';
    else cout << reg[D] << reg[A] << reg[B] << "0\n";
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
    int N;
    cin >> N;
    while (N--) solve();
    return 0;
}




Python 3 소스코드


from sys import stdin, stdout
input = stdin.readline
print = stdout.write

OP = {"ADD": 0, "ADDC": 1, "SUB": 2, "SUBC": 3, "MOV": 4, "MOVC": 5,
      "AND": 6, "ANDC": 7, "OR": 8, "ORC": 9, "NOT": 10, "MULT": 12,
      "MULTC": 13, "LSFTL": 14, "LSFTLC": 15, "LSFTR": 16, "LSFTRC": 17,
      "ASFTR": 18, "ASFTRC": 19, "RL": 20, "RLC": 21, "RR": 22, "RRC": 23}

for _ in range(int(input())):
    opcode, *reg = input().split()
    print(bin(OP[opcode])[2:].zfill(5)+'0')
    print(bin(int(reg[0]))[2:].zfill(3))
    print(bin(int(reg[1]))[2:].zfill(3))
    if opcode[-1] == 'C':
        print(bin(int(reg[2]))[2:].zfill(4)+'\n')
    else:
        print(bin(int(reg[2]))[2:].zfill(3)+'0\n')




참고



반응형