problems / 175

The Register Machine

easy bit-manipulation simulation 1000 ms · 256 MB

The Register Machine

You are to simulate a simple machine with 8 registers and a program consisting of assembly-like instructions. Each register initially holds 0 and can store a 64-bit unsigned integer.

The machine executes instructions sequentially. Execute the program and output all values printed by PRINT commands.

Instructions

The machine supports the following instructions:

  • LOAD reg val: Set register reg to value val
  • ADD reg1 reg2: Add the value in register reg2 to register reg1 (reg1 += reg2)
  • SUB reg1 reg2: Subtract the value in register reg2 from register reg1 (reg1 -= reg2)
  • AND reg1 reg2: Bitwise AND registers reg1 and reg2, store in reg1 (reg1 &= reg2)
  • OR reg1 reg2: Bitwise OR registers reg1 and reg2, store in reg1 (reg1 |= reg2)
  • XOR reg1 reg2: Bitwise XOR registers reg1 and reg2, store in reg1 (reg1 ^= reg2)
  • SHL reg k: Shift the value in register reg left by k bits (reg <<= k)
  • SHR reg k: Shift the value in register reg right by k bits (reg >>= k)
  • PRINT reg: Output the decimal value of register reg on a new line
  • HALT: Stop execution

All arithmetic operations use 64-bit unsigned integers with standard wraparound on overflow. Shift operations with k >= 64 result in 0.

Input

The first line contains n (1 ≤ n ≤ 1000), the number of instructions.

The next n lines each contain one instruction in the format described above. Register indices are in the range [0, 7]. Values val and k are non-negative integers up to 10^18.

Output

Print each value from PRINT commands in the order they are executed, one per line.

Notes

  • The program is guaranteed to contain at least one HALT instruction and will halt before running more than n instructions.
  • All register indices in instructions refer to registers 0 through 7.

Example 1

Input

5
LOAD 0 42
PRINT 0
LOAD 1 10
ADD 0 1
HALT

Output

42

Example 2

Input

10
LOAD 0 15
LOAD 1 7
AND 0 1
PRINT 0
LOAD 2 255
XOR 2 0
PRINT 2
LOAD 3 1
SHL 3 3
PRINT 3
HALT

Output

7
248
8

Hints · reveal one at a time if you're stuck

Hint 1

Each instruction is a fixed operation on the 8 registers, so you can simulate the program directly, one instruction at a time, until HALT. Which operations could behave unexpectedly with values near 2^64?

Hint 2

Store the registers as unsigned 64-bit values so additions and subtractions wrap around. Handle shifts by 64 or more as producing 0 rather than relying on the language's shift operator.

report an issue Prefer your own editor? sooks prep 175 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.