[백준] 1753* 최단경로 (골드4)

AI·2025년 10월 1일

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int v, e, start;
    static ArrayList<ArrayList<Node>> graph = new ArrayList<ArrayList<Node>>();
    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());
        start = Integer.parseInt(br.readLine());
        for(int i=0;i<=v;i++){
            graph.add(new ArrayList<>());
        }
        for(int i=0;i<e;i++){
            st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int to = Integer.parseInt(st.nextToken());
            int w = Integer.parseInt(st.nextToken());
            graph.get(u).add(new Node(to,w));
        }
        // 시작점에서 각 정점으로 갈 수 있는 최단 거리 구하기 - 다익스트라
        Dijkstra();
    }

    static class Node{
        int to;
        int w;
        Node(int to, int w){
            this.to = to;
            this.w = w;
        }
    }
    static void Dijkstra(){
        long[] dist = new long[v+1];
        Arrays.fill(dist, Long.MAX_VALUE/4);
        PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingLong(node -> node.w));
        dist[start] = 0;
        pq.add(new Node(start,0));
        while (!pq.isEmpty()){
            Node cur = pq.poll();
            int u = cur.to;
            long du = cur.w;
            if(du != dist[u]) continue;
            for(Node e:graph.get(u)){
                int v = e.to;
                long nd = du+e.w;
                if(nd<dist[v]){
                    dist[v] = nd;
                    pq.add(new Node(v,(int)nd));
                }
            }
        }

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

0개의 댓글