#P5581. Gambling Machine Game

    ID: 18811 Type: Default 1000ms 256MiB

Gambling Machine Game

Gambling Machine Game

There are \(n\) persons playing a gambling machine game in turns. Initially, the \(i^{th}\) person has \(a_i\) dollars. The gambling machine is represented by a cyclic sequence of length \(m\) containing only \(1\) and \(-1\). When a person plays:

  • If the drawn value is \(1\), they win 1 dollar.
  • If the drawn value is \(-1\), they lose 1 dollar.

The turns proceed as follows: in the 1st round, person 1 uses the 1st element of the sequence; in the 2nd round, person 2 uses the 2nd element; in the 3rd round, person 3 uses the 3rd element; and so on. After person \(n\) plays, the turn goes back to person 1. Similarly, after the \(m^{th}\) element of the machine is used, the next element is the 1st one.

If in any round a person loses all their money (i.e. their balance becomes \(0\)), the game immediately ends. Your task is to determine in which round the game ends, or determine that the game will continue indefinitely.

inputFormat

The input consists of three lines:

  • The first line contains two integers \(n\) and \(m\) separated by a space.
  • The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) representing the initial money for each person.
  • The third line contains \(m\) integers representing the elements of the gambling machine sequence (each element is either \(1\) or \(-1\)).

outputFormat

Output a single integer: the round number when a person's balance becomes \(0\). If the game can continue indefinitely, output \(-1\).

sample

2 3
1 1
-1 1 -1
1