Editorial for WC '18 Contest 1 S1 - Inspiration
Submitting an official solution before solving the problem yourself is a bannable offence.
The most direct solution involves iterating over all desks in the grid, and for each type-2 student encountered, iterating over all desks that they can see and checking if a type-1 student is sitting at any of them. Unfortunately, this approach is too slow to receive full marks. There can be up to type-2 students, and the average number of desks within view of each one is on the order of
, meaning that the time complexity of this solution is
.
If we assume that , then we can come up with a faster solution as follows. For each column, we can iterate through its desks in order from front to back, while maintaining a boolean variable
indicating if there have been any type-1 students so far (initially set to false). When we encounter a type-1 student, we should set
to true, and when we encounter a type-2 student, we know that they can be inspired if and only if
is currently true. The time complexity of this solution is
, which is fast enough.
This approach can then be generalized to working for any value of as follows. Let's swap out
for a variable
which represents the row of the most recent (furthest-back) type-1 student encountered so far (initially set to a very negative value). When we encounter a type-1 student at row
, we should set
to be equal to
, and when we encounter a type-2 student at row
, we know that they can be inspired if and only if
.
Comments