Workout for a Dumbbell

Simulate Jim's three passes over 10 machines where each machine already has a repeating user, and Jim waits whenever the machine is busy.

Medium4SimulationMathImplementationNo attempts yetTime limit2sMemory limit512 MB

Problem

Jim Ratt has joined a local fitness center. His workout is a sequence of 10 machines, numbered 1 to 10, that he goes through three times. For each machine he has a fixed usage time and a fixed recovery time that he takes right after using that machine, and both values are the same on all three passes.

Jim is not the only person in the center. Whenever he shows up there are exactly 10 other people, and person ii uses machine ii and nothing else. Person ii first starts using machine ii at time tit_i, uses it for uiu_i, rests for rir_i, and then immediately wants to use the same machine again, repeating this forever. A machine holds one person at a time. Anyone who wants a busy machine waits and starts the instant it becomes free. If Jim and the other person want to start on the same machine at the same moment, Jim lets the other person go first.

Jim is ready to use machine 1 at time 00. After he finishes his usage time on a machine he takes his recovery time for that machine, then moves to the next machine with no travel time. Write a program that computes when Jim finishes his workout.

Input

The first line contains 20 integers. The first two are Jim's usage time and recovery time for machine 1, the next two are for machine 2, and so on through machine 10.

Each of the next 10 lines contains three integers uu, rr, tt. Line kk gives the usage time uu, the recovery time rr, and the first start time tt of the person who uses machine kk.

All usage and recovery times satisfy 1u,r5×1061 \le u, r \le 5 \times 10^6, and every start time satisfies t5×106|t| \le 5 \times 10^6.

Output

Print the time when Jim finishes his workout, that is, the moment he finishes his usage time on machine 10 for the third time. Do not count his recovery time for that last machine.