Halting Machine
Time limit2sMemory limit512 MB
Parse N goto statements, build a directed graph, and print the longest path length from line 0 to line N, or infinity if a cycle is reachable on some path to N.
- Level
Medium6 of 10
- Topics
- Graph, Dynamic programming, Topological sort, Implementation
- Solved
- No attempts yet
Problem
The halting problem asks whether a program, given its source and its input, eventually finishes or runs forever. Alan Turing proved in 1936 that no general algorithm decides this for every pair of a program and an input, so a machine that takes an arbitrary program and reports whether it halts cannot exist. Restrict the language enough and the question becomes decidable. Language X, defined below, is such a language.
A program in language X consists of goto statements and nothing else. Lines are numbered through , and every line holds exactly one goto statement. A goto statement looks like this.
goto l1: c1, l2: c2, ..., lk: ck;
The statement moves execution to line when condition is true (). Conditions contain no spaces, and a space appears only after the goto keyword, after a colon, and after a comma.
The conditions are independent and each one is true for some input. So whenever execution reaches a line, it can move to any of the targets listed in that line's goto statement. Execution starts at line . The program halts when execution reaches line . One step is the execution of one goto statement, which moves to another line.
For each program, decide whether it halts, and when it halts under every combination of conditions, report the number of steps in the worst case.
Input
The first line contains the number of test cases ().
Each test case is one program. The first line of a test case contains the number of lines in the program (). The next lines each contain one goto statement, and the th of those lines is line of the program.
One goto statement lists at least and at most targets, and every target line number is at least and at most . The same target can appear more than once in one statement.
Output
For each test case, print the number of steps in the worst case on its own line. If some way of making the conditions true leaves the program running forever, print infinity without quotes instead of a step count.