Editorial for COCI '15 Contest 7 #5 Prosti


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Let's assume a fixed K (the number of consecutive numbers) and denote the number of happy numbers in the set \{i, i+1, \dots, i+K-1\} with f(i). It is clear that |f(i)-f(i+1)| \le 1.

Additionally, we can use brute force to find the first 150 consecutive composite numbers. If they begin with the number j, then it will hold f(j) = 0 for each K \le 150.

Lemma: Let a and b be integers and let f(a) \le L \le f(b). Then there exists x from the interval [a, b] such that f(x) = L.

The proof of this lemma is simple and is left as an exercise to the reader.

Now, let's work with the numbers K, L, M from the task. By applying the lemma to a = j and b = 1, we know that a solution must exist in the interval [1, j]. However, iterating over the entire interval would be too slow.

We use the binary search technique. Let's assume that we know for sure that our solution is in the interval [a, b]. Let c = (a+b)/2. Then we can apply the lemma to one of the intervals [a, c] or [c, b] and solve the task recursively.

The total time complexity of this algorithm is \mathcal O(Q \log j).


Comments

There are no comments at the moment.