Balanced Diet
Time limit2sMemory limit512 MB
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.
- Level
Hard8 of 10
- Topics
- Greedy, Math, Prefix sum, Number theory
- Solved
- No attempts yet
Problem
Every day Danny buys one candy at the candy store and eats it. The store sells kinds of candy, numbered from 1 to . Danny thinks a balanced diet matters, so he applies the same idea to his candy buying. For each kind he has fixed a target fraction , a real number with . He wants the share of kind among all the candies he has eaten to stay close to .
Write for the number of candies of kind that Danny has eaten, and let . The candies eaten so far are balanced when
holds for every .
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 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.
Input
The input has three lines. The first line has two integers (), the number of kinds of candy, and (), the number of candies Danny has already eaten.
The second line has positive integers . These numbers are proportional to , that is, . The sum of all is at most .
The third line has integers (), where is the kind of candy Danny bought and ate on day . Every prefix of this sequence, including the whole sequence, is balanced.
Output
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.