Algorithm, Problem Solving/백준(boj)

[백준][Java] 14170 - Counting Haybales

태오님 2024. 4. 4.

1. 문제 정보

https://www.acmicpc.net/problem/14170

 

14170번: Counting Haybales

Farmer John has just arranged his N haybales (1≤N≤100,000) at various points along the one-dimensional road running across his farm. To make sure they are spaced out appropriately, please help him answer Q queries (1≤Q≤100,000), each asking for the

www.acmicpc.net

난이도 : S3

유형 : 이분 탐색

시간 : O(QlogN), 정렬시간 제외


2. 문제 풀이

매우 기초적인 이분탐색 유형의 문제이다.

쿼리마다 구간 안에 있는  haybales 개수를 구하면 되는데

lowerbound와 upperbound 메서드를 이용하여 구해주면 된다.

 

lowerbound와 upperbound가 생소하다면 ~ 이상, ~ 초과라고 생각하면 쉽게 이해할 수 있다.


3. 문제 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static final StringBuilder sb = new StringBuilder();
    static StringTokenizer st;

    int N;
    int Q;
    int[] haybales;

    private int upperBound(int target) {

        int left = -1;
        int right = N;
        while (left + 1 < right) {
            int mid = (left + right) >> 1;
            if (haybales[mid] > target) {
                right = mid;
            } else {
                left = mid;
            }
        }

        return right;
    }

    private int lowerBound(int target) {

        int left = -1;
        int right = N;
        while (left + 1 < right) {
            int mid = (left + right) >> 1;
            if (haybales[mid] >= target) {
                right = mid;
            } else {
                left = mid;
            }
        }

        return right;
    }

    private void solution() throws IOException {

        st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        Q = Integer.parseInt(st.nextToken());

        haybales = new int[N];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            haybales[i] = Integer.parseInt(st.nextToken());
        }

        Arrays.sort(haybales);

        while (Q-- > 0) {
            st = new StringTokenizer(br.readLine());
            int targetA = Integer.parseInt(st.nextToken());
            int targetB = Integer.parseInt(st.nextToken());
            sb.append(upperBound(targetB) - lowerBound(targetA)).append("\n");
        }

        System.out.print(sb);
    }

    public static void main(String[] args) throws IOException {

        Main main = new Main();
        main.solution();
    }
}

댓글