[백준] 1504_최단경로

` 다익스트라

그래프를 만들고 다익스트라 활용. 1->n1->n2->n 과 1->n2->n1->n 두 가지 구하기


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.io.BufferedReader;
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 B1504 {
	static int N,E , n1,n2;
	static final int INF = 200000000;
	static List<int[]> list[];
	static boolean[] visit;
	static int[] dist;
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        E = Integer.parseInt(st.nextToken());

        list = new ArrayList[N + 1];
        for(int i = 0; i <= N; i++)
            list[i] = new ArrayList<>();

        dist = new int[N + 1];

        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());         
            list[s].add(new int[] {e,w});
            list[e].add(new int[]{s, w});
        }
        st = new StringTokenizer(br.readLine());
        n1 = Integer.parseInt(st.nextToken());
        n2 = Integer.parseInt(st.nextToken());

	// 2가지 경우를 구해서 최소값이 답이 됨.        
        int ans1 = 0;
        int ans2 = 0; 
        ans1 += dijkstra(1, n1);
        ans1 += dijkstra(n1, n2);
        ans1 += dijkstra(n2, N);
        
        
        ans2 += dijkstra(1, n2);
        ans2 += dijkstra(n2, n1);
        ans2 += dijkstra(n1, N);
        if (ans1 >= INF && ans2 >= INF) {
            System.out.println(-1);
            return;
        }
        System.out.println(Math.min(ans1, ans2));
	}
	
	private static int dijkstra(int start, int end){
	
		// 거리와 방문 여부 초기화        
		Arrays.fill(dist, INF);
        visit = new boolean[N+1] ;
        
	// 우선 순위 큐를 활용한 다익스트라
        PriorityQueue<int []> queue = new PriorityQueue<>((o1,o2) ->o1[1]-o2[1]);
        queue.add(new int[] {start, 0});
        dist[start] = 0;

        while (!queue.isEmpty()){
            int[] cur = queue.poll();
            int next = cur[0];
            int cost = cur[1];

            if(visit[next] == true) continue;
            visit[next] = true;

            for(int i = 0; i < list[next].size(); i++){
                int nextN = list[next].get(i)[0];
                int nextW = list[next].get(i)[1];
                
                if(!visit[nextN] && dist[nextN] > cost + nextW){
                    dist[nextN] = cost + nextW;
                    queue.add(new int[]{nextN, dist[nextN]});
                }
            }
        }
        return dist[end];
    }
}
  • 스터디 중 a로 갔다가 다시 1로 돌아오고 b로 가는 게 최단경로일 수 있지 않냐는 질문이 나옴. -> a에서 b로 갈 때 이미 최단경로임이 보장됨.(즉 a와 b 사이에 1이 있을 수도 없을 수도 있지만 상관없이 최단경로)
updatedupdated2021-04-112021-04-11
Load Comments?