Resources
| Resources | |||||
|---|---|---|---|---|---|
| Python | |||||
| GFG | |||||
Note that the video above covers both binary search modules.
Please check the Binary Search module for additional resources (though they cover additional material not part of this module).
Introduction
Example - Counting Haybales
Focus Problem – try your best to solve this problem before continuing!
View Internal SolutionExplanation
As each of the points are in the range , storing locations of haybales in a boolean array and then taking prefix sums of that would take too much time and memory.
Instead, let's place all of the locations of the haybales into a list and sort it. Now we can use binary search to count both the number of haybales with position at most and the number of haybales with position less than in time, and then subtract these two quantities to get the final answer.
Implementation (Without Built-in Functions)
Time Complexity:
def at_most(x: int) -> int:lo = 0hi = len(bales)while lo < hi:mid = (lo + hi) // 2if bales[mid] <= x:lo = mid + 1else:hi = midreturn lo
Implementation (With Built-in Functions)
Time Complexity:
We can use the builtin
bisect.bisect
function.
from bisect import bisectinp = open("haybales.in", "r")out = open("haybales.out", "w")bale_num, query_num = map(int, inp.readline().split())bales = sorted(list(map(int, inp.readline().split())))for _ in range(query_num):start, end = map(int, inp.readline().split())print(bisect(bales, end) - bisect(bales, start - 1), file=out)
Problems
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| CF | Easy | Show Tags2P, Binary Search | ||||
| Silver | Easy | Show TagsBinary Search | ||||
Module Progress:
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!