Svađa
The local zoo has acquired a large open garden in which animals may freely move as in their natural habitats and entertain visitors with their usual shenanigans. The most popular animals are monkeys. With their climbing and jumping and other skills, they delightold and young visitors alike. One species of monkey has specialized in climbing tall trees and picking off coconuts. Another specieshas specialized in breaking them open.
There are N monkeys of the first type (numbered 1 through N) and M monkeys of the second type(numbered 1 through M).
Monkey k of the first type takes Ak seconds to find a good spot on the tree, after which it picks off its first coconut. After that the monkey produces a new coconut every Bk seconds. Monkey k of the second type takes Ck seconds to find a good spot on the tree, after which it picks off its first coconut. After that the monkey produces a new coconut every Dk seconds.
Unfortunately, the second type of monkey is extremely aggressive so the two types may not be in the garden at the same time. Therefore, zoo keepers will chase away the first type of monkeys as soon as they have picked off all the coconuts. Similarly, if monkeys of the same type stay too long after opening all the coconuts, fights will ensue. Because of that, zoo keepers will send them away as soon as they have opened all the coconuts.
The zoo keepers first arrive immediately after all coconuts have been picked,
and again immediately after the monkeys open them all. The time needed for monkeys to enter or leave the garden is also negligibly small. Tomislav especially likes the second type of monkey, but can never guess when to arrive in order to see them. Help him calculate the time when the second type arrives if he knows the total time that monkeys spent in the garden, but does not know the number of coconuts in the garden.
Input:
12
1
3 1
1
5 1 Output:
5 Input:
20
2
3 2
1 3
3
3 1
4 1
5 1 Output:
13 Submit solution
Coming laterThe grading service will be connected in a later migration step. You can inspect the task and your previous results now.