[JAVA] 백준 (골드4) 1916번 최소비용 구하기

AIR·2024년 5월 13일
0

코딩 테스트 문제 풀이

목록 보기
100/135

링크

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


문제 설명

정답률 32.431%
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째 줄에는 우리가 구하고자 하는 구간 출발점의 도시번호와 도착점의 도시번호가 주어진다.
    • 출발점에서 도착점을 갈 수 있는 경우만 입력으로 주어진다.

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


출력 예제

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

4


풀이

최단경로 문제랑 완전 동일하다. 시작점과 도착점이 주어지고, 최단 거리를 구하는 문제이므로 다익스트라 알고리즘을 사용한다.

코드

import static java.util.Comparator.comparingInt;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

//백준
public class Main {

    static List<List<Edge>> adjList = new ArrayList<>();
    static int[] dist;
    static boolean[] visited;

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

        System.setIn(new FileInputStream("src/input.txt"));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        int N = Integer.parseInt(br.readLine());  //도시의 개수
        int M = Integer.parseInt(br.readLine());  //버스의 개수
        dist = new int[N + 1];
        visited = new boolean[N + 1];

        for (int i = 0; i <= N; i++) {
            adjList.add(new ArrayList<>());
        }

        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());  //출발 도시
            int b = Integer.parseInt(st.nextToken());  //도착 도시
            int c = Integer.parseInt(st.nextToken());  //비용

            adjList.get(a).add(new Edge(b, c));
        }

        st = new StringTokenizer(br.readLine());
        int start = Integer.parseInt(st.nextToken());
        int destination = Integer.parseInt(st.nextToken());

        dijkstra(start);

        System.out.println(dist[destination]);
    }

    static void dijkstra(int node) {
        Arrays.fill(dist, Integer.MAX_VALUE);

        PriorityQueue<Edge> pq = new PriorityQueue<>(comparingInt(Edge::getWeight));
        pq.add(new Edge(node, 0));
        dist[node] = 0;

        while (!pq.isEmpty()) {
            Edge cur = pq.poll();
            int curNode = cur.to;

            //방문하지 않은 노드일 경우
            if (!visited[curNode]) {
                visited[curNode] = true;

                for (Edge next : adjList.get(curNode)) {
                    int nextNode = next.to;
                    int nextWeight = next.weight;
                    int newDist = dist[curNode] + nextWeight;
                    if (dist[nextNode] > newDist) {
                        dist[nextNode] = newDist;
                        pq.add(new Edge(nextNode, dist[nextNode]));
                    }
                }
            }
        }
    }

    static class Edge {
        int to;
        int weight;

        public Edge(int to, int weight) {
            this.to = to;
            this.weight = weight;
        }

        public int getWeight() {
            return weight;
        }
    }
}
profile
백엔드

0개의 댓글