Official

E - Apple Baskets on Circle Editorial by en_translator


This problem can be solved in a total of \(O(N\log K)\) time using binary search.

When Takahashi made exactly \(mN\) actions, let’s say he made “\(m\) laps.”
For a fixed \(m\), one can find easily in an \(O(N)\) time how many apples Takahashi ate and how many apples remain in each basket right after he made \(m\) laps.
Therefore, by doing binary search for \(m\) by the condition “whether Takahashi will eat more than \(K\) apples,” one can find how many laps Takahashi will make before he eats \(K\) apples in a total of \(O(N\log K)\) time. Since the remainder can be naively simulated in a total of \(O(N)\) time, we can solve the problem in a total of \(O(N\log K)\) time.

Sample code (C)

Bonus: solve it in a total of \(O(N\log N)\) time.

posted:
last update: