Halting Problem
Time limit3sMemory limit512 MB
Given N states that add b or d to an integer x depending on whether x equals a, find the step count to reach state N+1 from state 1, or print -1.
- Level
Medium7 of 10
- Topics
- Simulation, Math, Hash map
- Solved
- No attempts yet
Problem
In the Republic of Finite Loop, a unique law is enforced. Under the law, programs that never halt are regarded as viruses. Releasing such a program is a cybercrime. So, you want to make sure that your software products always halt under their normal use.
It is widely known that there is no algorithm that can determine whether an arbitrary program halts for an arbitrary input. Fortunately, your products are based on a simple computation model given below. So, you can write a program that tells whether a given program based on the model will eventually halt for a given input.
The computation model has one variable and states, numbered 1 through . The variable can store any integer value. State means that the program has terminated. For each integer (), the behavior of the program in state is described by five integers , , , , and . Here and are indices of states.
When the program starts, its state is set to 1, and is set to , the input to the program. When the program is in state (), one of the following happens in one execution step:
- If is equal to , the value of changes to and the program state becomes .
- Otherwise, the value of changes to and the program state becomes .
The program terminates when its state becomes .
Write a program that determines whether a given program eventually halts for a given input. If it halts, compute how many steps it executes. The initialization is not counted as a step.
Input
The input consists of a single test case in the following format.
N x0
a1 b1 c1 d1 e1
.
.
.
aN bN cN dN eN
The first line contains two integers () and (). The program has states. Each of the next lines contains five integers , , , , and that determine the behavior of the program in state . The integers , , and are between and inclusive, and and are between 1 and inclusive.
Output
If the program eventually halts for the given input, output a single integer on a line: the number of steps executed until the program terminates. Since the number may be very large, output it modulo .
Output if the program never halts.