C - Illuminate Buildings 解説 by en_translator
First, consider the following problem:
(Problem X) at most how many buildings can be chosen so that:
- the chosen buildings have the same height, and
- the chosen buildings are contiguous?
This can be solved in \(O(N)\) time by scanning the buildings from the front.
Pseudocode
ans=0
height=0
crrent=0
for i in 1..N:
if height!=H[i]:
crrent=0
height=H[i]
crrent+=1
ans=max(ans,crrent)
print(ans)
Next, consider the following problem.
(Problem X) at most how many buildings can be chosen so that:
- the chosen buildings have the same height, and
- the chosen buildings are chosen at the interval of \(K\)?
The buildings that can be chosen at the same time can be divided into the following \(K\) disjoint groups:
- \(1,\ K+1,\ 2K+1,\ 3K+1\ldots\)
- \(2,\ K+2,\ 2K+2,\ 3K+2\ldots\)
- \(3,\ K+3,\ 2K+3,\ 3K+3\ldots\)
- \(\dots\)
So it is sufficient to solve (Problem X) for these \(K\) independent groups.
Finding the answer for each group costs \(O(N/K)\) time, which is repeated \(K\) times, so the overall complexity is \(O(N)\).
Finally, we consider the original problem. By solving (Problem Y) for all \(K=1,2,\ldots,\) the answer can be found in a total of \(O(N^2)\) time.
投稿日時:
最終更新: