알고리즘

[BOJ] 최소비용

winwin-k9 2024. 4. 16. 22:19

문제

N개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 M개의 버스가 있다.

우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다.

A번째 도시에서 B번째 도시까지 가는데 드는 최소비용을 출력하여라. 도시의 번호는 1부터 N까지이다.

풀이

목적지와 출발지에 따른 최소비용을 구하는 문제이다.
즉, 다익스트라를 이용하여 최소 비요을 구해야 한다.

주의할 점은 각 노드간의 관계가 출발과 도착 관계로 이루어져있다.
즉, 양반향이 아닌 단방향의 그래프 관계임을 주의하자.

다익스트라를 이해했다고 생각했는데 다시 구현하려고 하다보니 헷갈리는 부분을 다시 잡을 수 있었다.

import java.lang.*;
import java.io.*;
import java.util.*;

class Main {
    static boolean[] visited;
    static int[] distance;
    static int MAX_INT = 100000000;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str = br.readLine().split(" ");
        int N = Integer.parseInt(str[0]);
        str = br.readLine().split(" ");
        int M = Integer.parseInt(str[0]);
        List<Node>[] list = new List[N + 1];
        distance = new int[N + 1];
        visited = new boolean[N + 1];

        for (int i = 1; i <= N; i++) {
            list[i] = new ArrayList<>();
            distance[i] = MAX_INT;
        }

        for (int i = 0; i < M; i++) {
            str = br.readLine().split(" ");
            int a = Integer.parseInt(str[0]);
            int b = Integer.parseInt(str[1]);
            int cost = Integer.parseInt(str[2]);
            list[a].add(new Node(cost, b));
        }

        str = br.readLine().split(" ");
        int start = Integer.parseInt(str[0]);
        int end = Integer.parseInt(str[1]);

        dijkstra(start, list);

        System.out.println(distance[end]);
    }

    static void dijkstra(int startNode, List<Node>[] list) {
        PriorityQueue<Node> queue = new PriorityQueue<>(((o1, o2) -> o1.cost - o2.cost));
        queue.add(new Node(0, startNode));
        distance[startNode] = 0;

        while (!queue.isEmpty()) {
            Node currentNode = queue.poll();

            if (visited[currentNode.index]) {
                continue;
            }
            visited[currentNode.index] = true;

            for (Node node : list[currentNode.index]) {
                if (distance[node.index] > node.cost + distance[currentNode.index]) {
                    distance[node.index] = node.cost + distance[currentNode.index];
                    queue.add(new Node(distance[node.index], node.index));
                }
            }
        }
    }

    static class Node {
        int cost;
        int index;

        public Node(int cost, int index) {
            this.cost = cost;
            this.index = index;
        }
    }
}

https://github.com/Win-9/Algorism/tree/main/BOJ/%EC%B5%9C%EC%86%8C%EB%B9%84%EC%9A%A9%20%EA%B5%AC%ED%95%98%EA%B8%B0

728x90