Problem A
Balanced Diet
Time limit: 2 seconds
Every day, Danny buys one sweet from the candy store and eats it. The store has m types of sweets,
numbered from 1 to m. Danny knows that a balanced diet is important and is applying this concept to
his sweet purchasing. To each sweet type i, he has assigned a target fraction, which is a real number f
i
(0 < f
i
≤ 1). He wants the fraction of sweets of type i among all sweets he has eaten to be roughly
equal to f
i
. To be more precise, let s
i
denote the number of sweets of type i that Danny has eaten, and
let n =
P
m
i=1
s
i
. We say the set of sweets is balanced if for every i we have
nf
i
− 1 < s
i
< nf
i
+ 1.
Danny has been buying and eating sweets for a while and during this entire time the set of sweets
has been balanced. He is now wondering how many more sweets he can buy while still fulfilling this
condition. Given the target fractions f
i
and the sequence of sweets he has eaten so far, determine how
many more sweets he can buy and eat so that at any time the set of sweets is balanced.
Input
The input consists of three lines. The first line contains two integers m (1 ≤ m ≤ 10
5
), which is the
number of types of sweets, and k (0 ≤ k ≤ 10
5
), which is the number of sweets Danny has already
eaten.
The second line contains m positive integers a
1
, . . . , a
m
. These numbers are proportional to f
1
, . . . , f
m
,
that is, f
i
=
a
i
P
m
j=1
a
j
. It is guaranteed that the sum of all a
j
is no larger than 10
5
.
The third line contains k integers b
1
, . . . , b
k
(1 ≤ b
i
≤ m), where each b
i
denotes the type of sweet
Danny bought and ate on the i
th
day. It is guaranteed that every prefix of this sequence (including the
whole sequence) is balanced.
Output
Display the maximum number of additional sweets that Danny can buy and eat while keeping his diet
continuously balanced. If there is no upper limit on the number of sweets, display the word forever.
Sample Input 1 Sample Output 1
6 5
2 1 6 3 5 3
1 2 5 3 5
1
Sample Input 2 Sample Output 2
6 4
2 1 6 3 5 3
1 2 5 3
forever
ACM-ICPC World Finals 2016 Problem A: Balanced Diet 1