There are $N$ ($1 \le N \le 1000$) cows, numbered $1$ through $N$, taking part in an unusual relay race in which several cows may run at the same time.
Before time $t = 0$, every cow waits at the starting line. Each cow runs exactly one lap around a circular track whose finish line is the same as its starting line.
At time $t = 0$, cow $1$ starts running and crosses the starting line again exactly $L_1$ seconds later. In general, cow $i$ takes $L_i$ ($1 \le L_i \le 1000$) seconds to complete one lap. The instant a cow crosses the starting line at the end of her lap, she signals $M_i$ ($0 \le M_i \le N$) other cows $A_{i1}, A_{i2}, \dots, A_{iM_i}$ to start running immediately.
Each signaled cow begins her own lap at that moment and, when she finishes, performs her own signaling. A cow may be signaled by several different cows, but she runs only one lap, so every signal after the first one she receives is ignored. Every cow is guaranteed to be signaled at least once.
Determine the total race time: the moment at which the last cow finishes her lap.
Consider a race with $5$ cows. The table lists each cow's id $i$, her lap time $L_i$, the number of cows $M_i$ she signals when she finishes, and the (possibly empty) list of those cows $A_{i*}$:
i L_i M_i A_i*
1 4 2 2 4
2 3 3 1 3 4
3 7 1 5
4 4 2 3 5
5 1 0
Starting cow $1$ at time $0$ produces the following timeline of events:
| Time | Event |
|---|---|
| 0 | Cow 1 starts running |
| 4 | Cow 1 finishes and signals cows 2 and 4 |
| 4 | Cow 2 starts running (finishes at 4 + 3 = 7) |
| 4 | Cow 4 starts running (finishes at 4 + 4 = 8) |
| 7 | Cow 2 finishes and signals cows 1, 3, and 4 |
| 7 | Cows 1 and 4 ignore the repeated signal |
| 7 | Cow 3 starts running (finishes at 7 + 7 = 14) |
| 8 | Cow 4 finishes and signals cows 3 and 5 |
| 8 | Cow 3 ignores the repeated signal |
| 8 | Cow 5 starts running (finishes at 8 + 1 = 9) |
| 9 | Cow 5 finishes and has no cow to signal |
| 14 | Cow 3 finishes and signals cow 5 |
| 14 | Cow 5 ignores the repeated signal |
| 14 | All cows have finished |
The race therefore lasts $14$ seconds.