Gems in the maze
InterviewTime limit3sMemory limit2048 MB
Find the longest run of distinct chambers reachable by repeatedly following the tunnel from v to (a*v^2 + b*v + c) mod n.
Problem
Scrooge McDuck has a new plan to increase his wealth. He found ancient ruins with an extraordinary maze. The maze consists of chambers numbered through . Each chamber contains exactly one gem. Chambers are connected by one-way tunnels. Each chamber has exactly two outgoing tunnels: one leads to the chamber numbered , and the other brings you out of the maze.
You can enter the maze at any chamber, move along the tunnels, and collect the gems. Once you leave the maze, the self-destruct mechanism triggers, the ceiling collapses, and every gem you did not collect is lost forever.
Scrooge wants to know the maximum number of gems he can take from the maze.
Input
The first line of the input contains four integers , , , and , which describe one particular maze.
Output
Output a single line containing one integer: the maximum number of gems that can be taken from the maze.
Hint
The starting chamber matters. For instance, in the first test case Scrooge starts in chamber . His only two options are a tunnel that leads back to chamber and a tunnel that leads outside, which is not much of a choice. A much better strategy is to start in chamber and follow the path outside.