알고리즘/백준

[백준] 1753번 : 최단경로

코딍코딍 2024. 1. 16. 22:38

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

 

1753번: 최단경로

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가

www.acmicpc.net

 

문제

방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. , 모든 간선의 가중치는 10 이하의 자연수이다.

 

입력

첫째 줄에 정점의 개수 V 간선의 개수 E 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V) 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 간선을 나타내는 개의 정수 (u, v, w) 순서대로 주어진다. 이는 u에서 v 가는 가중치 w 간선이 존재한다는 뜻이다. u v 서로 다르며 w 10 이하의 자연수이다. 서로 다른 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다.

 

출력

첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF 출력하면 된다.첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF 출력하면 된다.

 


소스코드

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

class Main {
    static ArrayList<ArrayList<Node>> g = new ArrayList();
    static int dist[]; // 최단 거리
    static boolean visited[];
    static int v, e, k;

    static class Node implements Comparable<Node> {
        int end, weight;

        public Node(int end, int weight) {
            this.end = end;
            this.weight = weight;
        }

        @Override
        public int compareTo(Node o) {
            return weight - o.weight;
        }
    }

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

        v = Integer.parseInt(st.nextToken());
        e = Integer.parseInt(st.nextToken());
        k = Integer.parseInt(br.readLine());

        dist = new int[v + 1];
        visited = new boolean[v + 1];
        for (int i = 0; i <= v; i++) {
            g.add(new ArrayList<>());
        }

        for (int i = 0; i < e; i++) {
            st = new StringTokenizer(br.readLine());
            int s = Integer.parseInt(st.nextToken());
            int e = Integer.parseInt(st.nextToken());
            int w = Integer.parseInt(st.nextToken());

            g.get(s).add(new Node(e, w));
        }

        dijkstra(k);
        for (int i = 1; i <= v; i++) {
            if (dist[i] == Integer.MAX_VALUE) System.out.println("INF");
            else System.out.println(dist[i]);
        }
    }

    static void dijkstra(int start) {
        Arrays.fill(dist, Integer.MAX_VALUE);
        Arrays.fill(visited, false);

        PriorityQueue<Node> pq = new PriorityQueue<>();
        pq.add(new Node(start, 0));
        dist[start] = 0;

        while (!pq.isEmpty()) {
            Node node = pq.poll();
            int cur = node.end;

            if (!visited[cur]) {
                visited[cur] = true;

                for (Node next : g.get(cur)) {
                    if (!visited[next.end] && dist[next.end] > dist[cur] + next.weight) {
                        dist[next.end] = dist[cur] + next.weight;
                        pq.add(new Node(next.end, dist[next.end]));
                    }
                }
            }
        }
    }
}

 

해결 방법

  1. 다익스트라 알고리즘을 사용하면 쉽게 해결할 수 있다.