Given proportional target fractions and a balanced eating history, find how many more candies can be added with every prefix staying balanced, or report forever.
Hard8GreedyMathPrefix sumNumber theoryNo attempts yetTime limit2sMemory limit512 MBEvery day Danny buys one candy at the candy store and eats it. The store sells m kinds of candy, numbered from 1 to m. Danny thinks a balanced diet matters, so he applies the same idea to his candy buying. For each kind i he has fixed a target fraction fi, a real number with 0<fi≤1. He wants the share of kind i among all the candies he has eaten to stay close to fi.
Write si for the number of candies of kind i that Danny has eaten, and let n=∑i=1msi. The candies eaten so far are balanced when
nfi−1<si<nfi+1
holds for every i.
Danny has been buying and eating candy for a while, and the whole time the candies eaten have been balanced. He now wonders how many more he can buy. Given the target fractions fi and the order in which he has eaten so far, find how many more candies Danny can buy and eat so that the candies eaten are balanced at every moment.
The input has three lines. The first line has two integers m (1≤m≤105), the number of kinds of candy, and k (0≤k≤105), the number of candies Danny has already eaten.
The second line has m positive integers a1,…,am. These numbers are proportional to f1,…,fm, that is, fi=∑j=1majai. The sum of all aj is at most 105.
The third line has k integers b1,…,bk (1≤bi≤m), where bi is the kind of candy Danny bought and ate on day i. Every prefix of this sequence, including the whole sequence, is balanced.
Print the largest number of extra candies Danny can buy and eat while the candies eaten stay balanced at every moment. If there is no upper bound on that number, print forever.