[BOJ]1753 -최단경로(G4)

suhyun·2023년 1월 17일
0

백준/프로그래머스

목록 보기
60/81

문제 링크

1753-최단경로


입력

첫째 줄에 정점의 개수 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를 출력하면 된다.


문제 풀이

다익스트라 알고리즘을 이용하는 기본적인 문제다.

우선 list 에 도착점과 가중치로 이루어진 Node를 저장
그리고 PriorityQueue에 Node들이 들어가면 그것들이 가지고 있는 w에 따라서 정렬이 되고
가장 작은 w를 가지고 있는 Node부터 처리하기 위해서 PriorityQueue로 정렬하여 사용

if (dist[next.v] > cur.w + next.w) {
	dist[next.v] = cur.w + next.w;
	pq.add(new Node(next.v, dist[next.v]));
}

위의 부분이 시작점 -> cur -> next시작점 -> next 의 가중치를 비교해 dist에 저장하는 코드이다.

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

class Node implements  Comparable<Node>{
    int v, w;

    Node(int v, int w) {
        this.v = v;
        this.w = w;
    }

    @Override
    public int compareTo(Node n){
        return this.w - n.w;
    }
}

public class Main {

    final static int INF = 10000001;
    static int V, E, K;
    static int dist[];
    static ArrayList<Node> list[];

    public static void main(String[] args) throws IOException {
        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()) - 1;

        list = new ArrayList[V];
        dist = new int[V];

        for (int i = 0; i < V; i++) {
            list[i] = new ArrayList<Node>();
            dist[i] = INF;
        }

        for (int i = 0; i < E; i++) {
            st = new StringTokenizer(br.readLine());

            int u = Integer.parseInt(st.nextToken()) - 1;
            int v = Integer.parseInt(st.nextToken()) - 1;
            int w = Integer.parseInt(st.nextToken());

            list[u].add(new Node(v, w));
        }
        dijkstra(K);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i<V; i++){
            if(dist[i] == INF)
                sb.append("INF").append("\n");
            else
                sb.append(dist[i]).append("\n");
        }
        System.out.print(sb);
    }

    static void dijkstra(int start) {
        PriorityQueue<Node> pq = new PriorityQueue<>();
        dist[start] = 0;
        pq.add(new Node(start, 0));

        while (!pq.isEmpty()) {
            Node cur = pq.poll();
            int length = list[cur.v].size();

            for (int i = 0; i < length; i++) {
                Node next = list[cur.v].get(i);

                if (dist[next.v] > cur.w + next.w) {
                    dist[next.v] = cur.w + next.w;
                    pq.add(new Node(next.v, dist[next.v]));
                }

            }
        }
    }
}
profile
꾸준히 하려고 노력하는 편 💻

0개의 댓글