Simulate a tiny accumulator machine through its fetch-decode-execute cycle. It has one register, ACC, a program counter starting at 0, and 100 memory cells (addresses 0 to 99), all starting at 0. Instructions are numbered from 0.
| Instruction | Meaning |
|---|---|
LOADI v | ACC = v (v may be negative) |
LOAD a | ACC = memory[a] |
STORE a | memory[a] = ACC |
ADD a, SUB a | ACC = ACC + memory[a], ACC = ACC − memory[a] |
JMP n | continue at instruction n |
JZ n | if ACC is 0, continue at instruction n |
OUT | print ACC |
HALT | stop |
The machine also stops when it moves past the last instruction. Every test program stops within 1000 instructions.
Input
A line with n (1 ≤ n ≤ 100), then n instructions, one per line.
Output
One line for each OUT.
Examples
8 LOADI 10 STORE 0 LOADI 20 ADD 0 STORE 0 LOADI 30 ADD 0 OUT
60
11 LOADI 1 STORE 1 LOADI 3 STORE 0 LOAD 0 JZ 10 OUT SUB 1 STORE 0 JMP 4 HALT
3 2 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep pc = 0, acc = 0 and memory = [0] * 100.
Hint 2
Loop: if pc is past the last instruction, stop; otherwise fetch program[pc], add 1 to pc, then carry out the instruction.
Hint 3
JMP sets pc; JZ sets pc only when acc == 0; OUT prints acc; HALT stops.
Solution
Show one correct solution (try it yourself first)
n = int(input())
program = [input().split() for _ in range(n)]
memory = [0] * 100
pc, acc = 0, 0
while pc < len(program):
parts = program[pc]
pc += 1
op = parts[0]
arg = int(parts[1]) if len(parts) > 1 else 0
if op == "LOADI":
acc = arg
elif op == "LOAD":
acc = memory[arg]
elif op == "STORE":
memory[arg] = acc
elif op == "ADD":
acc += memory[arg]
elif op == "SUB":
acc -= memory[arg]
elif op == "JMP":
pc = arg
elif op == "JZ":
if acc == 0:
pc = arg
elif op == "OUT":
print(acc)
elif op == "HALT":
break