The Monkey Dance
InterviewTime limit1sMemory limit128 MB
Each monkey follows one outgoing arrow per step on a permutation; find the step count when all monkeys are back home, which is the LCM of the cycle lengths.
- Level
Medium4 of 10
- Topics
- Graph, Math, Simulation, Number theory
- Solved
- No attempts yet
Problem
The director of Hind Circus has decided to add a new act, the monkey dance, to the show. The monkey dance is performed by monkeys at the same time. On the ground there are circles labelled from to , and at the start each monkey sits on a different circle. There are arrows drawn between the circles so that exactly one arrow leaves each circle and exactly one arrow enters each circle.
Once the show starts, every time the ringmaster blows the whistle all monkeys simultaneously jump from their current circle to another circle by following the arrow that leaves their current circle. This is one step of the dance. The dance ends when every monkey has returned to the circle where it started. How many steps does the dance last?
Input
The input may contain several test cases. Each case begins with a line holding the number of circles , followed by lines that each contain a pair of integers between and . The pair , means there is an arrow from circle to circle . The input ends with a line whose value of is .
Output
For each test case, print the number of steps in the dance, one value per line.