[백준 / 골드5] 2110번 공유기 설치 (Java)

wannabeking·2022년 6월 18일
0

코딩테스트

목록 보기
19/155

문제 보기



사용한 것

  • 시간 복잡도를 통과하기 위한 이분 탐색
  • 이분 탐색 중 upper bound 사용


풀이 방법

  • 간격을 1부터 마지막 집의 X좌표 - 첫 집의 X좌표 까지 이진 탐색으로 가능한지 탐색
  • upper bound를 사용하여 불가능한 가장 작은 인덱스 구함
    • 일반적으로 정답은 upper bound 결과 값 - 1
    • 하지만 마지막 인덱스가 가능한 경우면 upper bound 값도 가능한 값


코드

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

public class Main {

    static int N;
    static int C;
    static int[] houseXs;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int[] size = Arrays.stream(br.readLine().split(" "))
            .mapToInt(Integer::parseInt)
            .toArray();
        N = size[0];
        C = size[1];
        houseXs = new int[N];
        for (int i = 0; i < N; i++) {
            houseXs[i] = Integer.parseInt(br.readLine());
        }

        Arrays.sort(houseXs);

        System.out.println(binarySearch());
    }

    public static int binarySearch() {
        int l = 1;
        int r = houseXs[N - 1] - houseXs[0];
        int m;
        while (l < r) {
            m = (l + r) / 2;
            if (isPossible(m)) {
                l = m + 1;
            } else {
                r = m;
            }
        }
        if (isPossible(r)) {
            r++;
        }

        return r - 1;
    }

    public static boolean isPossible(int length) {
        int ct = 1;
        int lastX = houseXs[0];
        for (int i = 1; i < N; i++) {
            int curX = houseXs[i];

            if (curX - lastX < length) {
                continue;
            }

            ct++;
            if (ct == C) {
                return true;
            }

            lastX = curX;
        }

        return false;
    }
}


profile
내일은 개발왕 😎

0개의 댓글