Tram
Time limit2sMemory limit512 MB
For each junction, find the greatest common divisor of all cycle lengths reachable from and returning to it, or -1 if no return is possible.
- Level
Hard8 of 10
- Topics
- Graph, DFS, Number theory, Implementation
- Solved
- No attempts yet
Statement
Byteman collects photos of old vehicles. One day, looking out of his window, he saw a rare old tram stopped at the stop right in front of his house, but it left before he could pick up his camera, so he missed the shot. He wants to be ready next time.
Byteman lives in Bytetown, which has junctions numbered from to , with one tram stop at each junction. Trams always arrive at whole minutes. Instead of checking the stop every single minute, Byteman decides to set his camera to photograph the stop every minutes, taking the moment the tram first appears as minute .
He wants the largest period such that, no matter which route the tram takes, every moment it returns to his stop is a multiple of . That way the camera never misses the tram.
Generalizing, for each junction define the value as follows. Suppose the tram appears at junction at minute and then travels along the tracks. is the largest integer such that, over every route the tram may take, every later moment at which the tram is again at junction is a multiple of .
The tram keeps moving as long as it can. It stops only when it reaches a junction with no outgoing track (a dead end); otherwise it may run forever. The time spent waiting at a stop is negligible.
If junction has no outgoing track, or if a tram leaving junction can never return to , then .
For every junction from to , compute .
Input
The first line contains two integers and (), separated by a single space: the number of junctions and the number of tracks. Junctions are numbered from to .
Each of the next lines contains three integers , , (, ), separated by single spaces. Each such track is one-way and lets a tram travel from junction to junction in minutes.
Both directions between a pair of junctions may exist, and is allowed (a loop at a single junction). For any given direction there is at most one track between a pair of junctions.
The time a tram spends waiting at a stop is negligible, and the tram travels as long as it can (until it reaches a dead end, or forever if it never does).
Output
Print integers, each on its own line. The -th line must contain .
Note

In the example above, a tram leaving junction can return after, for instance, , , or minutes. So, for the camera not to miss any appearance of the tram, it must be set to take a photo every two minutes, giving .