Sort the coordinates of the haybales.
Let be the number of haybales in the interval . Then, the number of haybales in the interval is equal to f(b) - f(a - 1).
Find the value of using binary search.
Algorithm implementation
Read the input data.
scanf("%d %d", &n, &q);
v.resize(n);
for (i = 0; i < n; i++)
scanf("%d", &v[i]);Sort the coordinates of the haybales.
sort(v.begin(), v.end());Process queries.
for (i = 0; i < q; i++)
{Find and print the number of haybales in the interval from to , inclusive.
scanf("%d %d", &a, &b);
res = upper_bound(v.begin(), v.end(), b) –
upper_bound(v.begin(), v.end(), a - 1);
printf("%d\n", res);
}Python implementation
import bisectRead the input data.
n, q = map(int, input().split())
v = list(map(int, input().split()))Sort the coordinates of the haybales.
v.sort()Process queries.
for _ in range(q):Find and print the number of haybales in the interval from to , inclusive.
a, b = map(int, input().split())
res = bisect.bisect_right(v, b) - bisect.bisect_right(v, a - 1)
print(res)