USACO Silver 2016 December - Counting Haybales

Authors: Albert Zhu, Kevin Sheng


Official Analysis (Java)

Implementation

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

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("haybales.in", "r", stdin);
int bale_num;
int query_num;
cin >> bale_num >> query_num;
vector<int> haybales(bale_num);

Java

import java.io.*;
import java.util.*;
public class Haybales {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("haybales.in"));
StringTokenizer initial = new StringTokenizer(in.readLine());
int baleNum = Integer.parseInt(initial.nextToken());
int queryNum = Integer.parseInt(initial.nextToken());

Python

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!