알고리즘(Algorithm)/백준(Baekjoon)

[백준 Baekjoon] 1826번 연료 채우기 - JAVA

나아가는중 2021. 12. 15. 15:28
반응형

문제 풀이

우선순위 큐를 활용하여 풀 수 있는 문제이다.

 

주유소 정보를 거리(a) 오름차순으로 저장하는 우선순위 큐를 사용하여 입력받는다.

예제의 주유소는 거리순으로 주어지지만, 항상 거리순으로 주어지지 않는다.

 

현재까지 갈 수 있는 거리의 주유소 중에서 가장 연료의 양이 많은 주유소를 방문해야 한다.

주유소 정보 stations에서 현재까지 갈 수 있는 거리(P) 내의 주유소 연료 양을 fuels에 추가한다.

fuels는 연료 양을 내림차순으로 저장하는 우선순위 큐이다.

 

fuels에서 하나를 방문(poll)하고 현재 갈 수 있는 거리(P)를 증가시킨다.

주유소를 방문하였으므로 answer도 1증가 시킨다.

 

현재 갈 수 있는 거리 P가 L을 넘으면 목적지까지 갈 수 있으므로 종료된다.

만약 fuels가 비어있다면 방문할 수 있는 주유소가 없고 목적지 L에 도착하지 못한 경우이다.

 

문제에서 주어진 예시로

P: 10, 0 ~ 10 사이에 갈 수 있는 주유소 중 최대 연료 양 = 4

P: 14, 0 ~ 14 사이에 갈 수 있는 주유소 중 최대 연료 양 = 5

P: 19, 0 ~ 19 사이에 갈 수 있는 주유소 중 최대 연료 양 = 10

P: 29, 목적지까지 갈 수 있으므로 종료.

 

소스 코드

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        int N = Integer.parseInt(br.readLine());
        PriorityQueue<GasStation> stations = new PriorityQueue<>();

        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());

            stations.add(new GasStation(a, b));
        }

        st = new StringTokenizer(br.readLine());
        int L = Integer.parseInt(st.nextToken());
        int P = Integer.parseInt(st.nextToken());

        PriorityQueue<Integer> fuels = new PriorityQueue<>(Collections.reverseOrder());
        int answer = 0;

        while (P < L) {
            while (!stations.isEmpty() && stations.peek().a <= P) {
                fuels.add(stations.poll().b);
            }

            if (fuels.isEmpty()) {
                System.out.println(-1);
                return;
            }

            answer++;
            P += fuels.poll();
        }

        System.out.println(answer);
    }

    public static class GasStation implements Comparable<GasStation> {
        int a;
        int b;

        public GasStation(int a, int b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public int compareTo(GasStation o) {
            return this.a - o.a;
        }
    }
}
반응형