Editorial for A Christmas Carol 3
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.
Submitting an official solution before solving the problem yourself is a bannable offence.
Authors:
The question can be boiled down into this: Find the biggest element less than or equal to . This can be done a number of ways.
One solution is to sort the array then binary search it for every query. If the element, was found, that is the turkey that must be bought. If it does not exist, the turkey that must be bought is the element directly preceding where the value would go in the arrays. This is sufficient to pass the first subtask.
Pseudocode:
int[] values <- input
sort(values)
for every query:
int q_i <- input
index <- binarySearch(values, q_i)
print(index)
Time Complexity: qlog(n)
Another approach is to construct an array, , that can be used to look up the result for every value of such that is the answer for . This allows for O(1) queries. For every value , set to then set the value of indices in to .
Pseudocode:
int[1000001] answers
int[] values <- input
for i = 0 to length(values):
answers[values[i]] <- values[i]
int answer <- answers[1]
for i = 2 to length(answers):
if answers[i] == 0:
answers[i] = answer
else
answer = answers[i]
for every query:
int q_i <- input
print(answers[q_i])
Comments