Official Analysis (Java)

Implementation

Time Complexity: O((N+Q)logN)\mathcal{O}((N+Q)\log N)

from bisect import bisect_left, bisect_right
with open("haybales.in") as read:
bale_num, query_num = [int(i) for i in read.readline().split()]
haybales = sorted(int(i) for i in read.readline().split())
ans = []
for _ in range(query_num):
start, end = [int(i) for i in read.readline().split()]
left = bisect_left(haybales, start)
right = bisect_right(haybales, end)
ans.append(right - left)
print("\n".join(str(a) for a in ans), file=open("haybales.out", "w"))

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!