B - 身長比べ / Height Comparison Editorial by admin
DeepSeek V3Overview
Given students lined up in order of their student numbers, a student is defined as a “looking-up student” if there exists a student before them who belongs to the tall group (height \(T\) or more) and whose height is greater than theirs. The problem asks us to find the number of such students.
Analysis
A naive approach would be, for each student \(i\), to check all previous students (\(j < i\)) to see if there exists a student with \(S_j \geq T\) and \(S_j > S_i\). However, this method has a time complexity of \(O(N^2)\), which would result in an extremely long execution time given the constraint that \(N\) can be up to \(10^6\).
An efficient solution is to maintain “the maximum height among tall group students encountered so far” as we scan the sequence from the beginning. For each student \(i\), if the maximum height of the tall group so far is greater than \(S_i\), then that student is a looking-up student. Since the processing for each student takes constant time, this approach solves the problem in linear time.
Algorithm
- Initialize variable
max_so_farto 0 (records the maximum height among tall group students encountered so far) - Initialize variable
countto 0 (counts the number of looking-up students) - Process students from number 1 to N in order:
- If the current student is not the first one (\(i > 0\)) and
max_so_faris greater than the current student’s height:- Increment
countby 1
- Increment
- If the current student belongs to the tall group (\(S_i \geq T\)):
- Compare
max_so_farwith the current height and update if necessary (if \(S_i > \text{max\_so\_far}\), setmax_so_far = S_i)
- Compare
- If the current student is not the first one (\(i > 0\)) and
- Output
count
In this algorithm, only students in the tall group can update max_so_far, so it always holds “the maximum height among tall group students encountered so far.”
Complexity
- Time complexity: \(O(N)\)
- Since each of the \(N\) students is processed exactly once
- Space complexity: \(O(N)\)
- An array is needed to store the height data, but only the space required for reading input
Implementation Notes
Note that the first student (\(i=0\)) cannot be a looking-up student since there are no students before them
The initial value of
max_so_faris set to 0 (this is fine since all heights are at least 1)It is important to perform the tall group check and the maximum value update in the correct order
Source Code
import sys
def main():
data = sys.stdin.read().split()
n = int(data[0])
T = int(data[1])
S = list(map(int, data[2:2+n]))
count = 0
max_so_far = 0
for i in range(n):
if i > 0 and max_so_far > S[i]:
count += 1
if S[i] >= T:
if S[i] > max_so_far:
max_so_far = S[i]
print(count)
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.
posted:
last update: