World's Worst Bus Schedule

No attempts yetTime limit1sMemory limit128 MB

Problem

You hate waiting. You are on your way to visit a relative in New Orleans, and the bus station you are standing in has the worst schedule you have ever seen. There are no arrival times and no departure times, only a list of how long each running bus takes to finish one route. So you pull out your laptop and write a program that tells you how long you have to wait for the next bus.

Every bus leaves the station at time 0 and drives its routes in the given order, again and again. It returns to the station the instant it finishes a route and leaves immediately for the next one. After the last route it starts over from the first. Counting from the moment you arrive, find the earliest time at which some bus is at the station and report how long you wait.

Input

The input is not empty and holds at most 100 data sets. No blank line separates the data sets.

A single data set has four parts.

  1. Start line. One line of the form START N, where N is the number of buses running. 1N201 \le N \le 20.
  2. Route duration lines. N lines follow, and each one holds the M route durations of a single bus, separated by spaces. 1M101 \le M \le 10, and M may differ from line to line. Every duration is an integer between 1 and 1000, inclusive.
  3. Arrival time line. One integer, the time at which you reached the station and began waiting, measured from time 0 when the buses began running. It is at least 0.
  4. End line. One line reading END.

A single line reading ENDOFINPUT follows the last data set.

Output

Print one line per data set: the number of time units you wait after arriving until the next bus reaches the station. You hate waiting, so you board the first bus that comes back.

Hint

  1. Every bus runs its routes without pause. When the last route ends, the bus starts again from the first one.
  2. If your arrival time falls exactly on a departure time of some bus, you board that bus right then. Every bus departs at time 0, so arriving at time 0 means waiting 0.