Hang or Not to Hang
Time limit1sMemory limit512 MB
Given a tiny assembly program with 32 boolean registers, arbitrary initial state, and nondeterministic RANDOM instructions, find the minimum number of cycles over all possible executions until STOP, or report HANGS.
- Level
Medium6 of 10
- Topics
- BFS, Bit manipulation, Simulation, Graph
- Solved
- No attempts yet
Problem
Little Tom is learning to program. He has just written a few programs but is afraid to run them, because he does not know whether they will ever stop. Help him.
This is harder than it looks, because Tom's programs may behave nondeterministically.
Given one of Tom's programs, decide whether it can stop, and if so, find the shortest possible time before it stops.
Tom's computer has 32 one-bit registers, numbered from 0 to 31, and a program of n instructions, numbered from 0 to n − 1.
Below, MEM[a] denotes the contents of register a, with 0 ≤ a, b < 32, 0 ≤ x < n, and 0 ≤ c ≤ 1.
The instruction set is as follows:
The last instruction of every program is always STOP (a program may contain more than one STOP). Every program starts at instruction 0. Before execution begins, the registers may hold arbitrary values. Each instruction (including STOP) takes one processor cycle.
Because of RANDOM instructions and the arbitrary initial register values, one program can run in many different ways. Among all runs that stop, report the smallest number of cycles. If no run ever stops, the program hangs.
Write a program that:
- reads Tom's program,
- computes the shortest possible running time,
- prints the result.
Input
The first line contains an integer n (1 ≤ n ≤ 16), the number of instructions in the program. Each of the next n lines contains one instruction in the format given above. The only whitespace characters in the program are single spaces between successive tokens of an instruction.
Output
Print a single line with the shortest possible running time, measured in processor cycles. If the program can never stop, print the word HANGS instead.