Розбір
Problem Author: | Pavlo Tsitsei |
Editorial by: | Pavlo Tsitsei |
Firstly, let's sort an array.
Consider a greedy solution for some . For the first integer in the set, we will choose the minimal element. Then let be the last chosen element. The next element will be the smallest integer from the array which is at least . And we will do this till there is such an integer.
Here is a proof of why it works. Let be a sequence that we get from the greedy solution and let be some better sequence (if we can get even better, then take a subsequence of it of elements). Then, we will prove that the greedy solution should get sequence . Clearly, there exists some , such that , because otherwise these sequences should be equal (there cannot exist index such that , since we always choose the smallest possible ). We will choose the smallest such . Then, is the smallest element which is good for us, so if we make equal to in sequence , it should also be good and it doesn't change the number of elements. If we do this till we can, at some moment we will see that the first elements are equal in and , but has also one more, so we get a contradiction.
So, how long does this algorithm work? We can make it in by iterating over all elements and updating the last elements. Using binary search, we can make it in , if we search for the next element in the sequence. This is already good enough (if you implement it using actual binary search and not ), but we can solve it in . It would be good for us, because in this case, the final complexity will be which is good. (Using binary search you will get ). To get for fixed , for each element , we can memorize the next element in the array which is at least . If we add to all elements (note that it will not change the answer), we can make an array of integers where the -th integer is the smallest number in the array which is at least . It can be computed in . Then, we can find the next element in thegreedy solution in just by looking at the -th element of the array.