ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 백준 1916번 최소 비용 구하기(자바) - 다익스트라
    코딩테스트 2022. 7. 4. 16:37

    최소비용 구하기 성공

     
    시간 제한메모리 제한제출정답맞힌 사람정답 비율
    0.5 초 128 MB 54175 16519 10739 32.117%

    문제

    N개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 M개의 버스가 있다. 우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다. A번째 도시에서 B번째 도시까지 가는데 드는 최소비용을 출력하여라. 도시의 번호는 1부터 N까지이다.

    입력

    첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스의 출발 도시의 번호가 주어진다. 그리고 그 다음에는 도착지의 도시 번호가 주어지고 또 그 버스 비용이 주어진다. 버스 비용은 0보다 크거나 같고, 100,000보다 작은 정수이다.

    그리고 M+3째 줄에는 우리가 구하고자 하는 구간 출발점의 도시번호와 도착점의 도시번호가 주어진다. 출발점에서 도착점을 갈 수 있는 경우만 입력으로 주어진다.

    출력

    첫째 줄에 출발 도시에서 도착 도시까지 가는데 드는 최소 비용을 출력한다.

    예제 입력 1 복사

    5
    8
    1 2 2
    1 3 3
    1 4 1
    1 5 10
    2 4 2
    3 4 1
    3 5 1
    4 5 3
    1 5
    

    예제 출력 1 복사

    4

    node 클래스에서 Comparable을 implements 하지 않으면 우선 순위를 정하지 못해 오류가 난다!

    또 다익스트라 메소드 안에서

    if (table[end] < now.getCost()) continue;

    문장을 통해 이미 최소값이 들어가있는 경우를 제외시켜주지 않으면 시간 초과가 발생한다.

     

    import java.util.*;
    
    class Node implements Comparable<Node>{
        private int end;
        private int cost;
        Node(int end, int cost) {
            this.end = end;
            this.cost = cost;
        }
    
        public int getEnd() {
            return end;
        }
    
        public int getCost() {
            return cost;
        }
    
        @Override
        public int compareTo(Node node) {
            if (this.getCost() < node.cost)
                return -1;
            return 1;
        }
    }
    public class Main {
        static int n;
        static int[] table;
        static ArrayList<ArrayList<Node>> graph;
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            n = sc.nextInt();
            int m = sc.nextInt();
            table = new int[n+1];
            graph = new ArrayList<>();
            for (int i = 0; i <= n; i++) {
                graph.add(new ArrayList<>());
            }
            for (int i = 0; i < m; i++) {
                int start = sc.nextInt();
                int end = sc.nextInt();
                int cost = sc.nextInt();
                graph.get(start).add(new Node(end, cost));
            }
            int sn = sc.nextInt();
            int en = sc.nextInt();
            Arrays.fill(table, (int)1e9);
            dijkstra(sn);
            System.out.println(table[en]);
        }
        static void dijkstra(int start) {
            PriorityQueue<Node> que = new PriorityQueue<>();
            que.offer(new Node(start, 0));
            table[start] = 0;
            while (!que.isEmpty()) {
                Node now = que.poll();
                int end = now.getEnd();
                if (table[end] < now.getCost()) continue;
                for (int i = 0; i < graph.get(end).size(); i++) {
                    int value = table[end] + graph.get(end).get(i).getCost();
                    if (value < table[graph.get(end).get(i).getEnd()]) {
                        table[graph.get(end).get(i).getEnd()] = value;
                        que.offer(new Node(graph.get(end).get(i).getEnd(), value));
                    }
                }
            }
        }
    }
Designed by Tistory.