-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDH_72413.java
More file actions
92 lines (70 loc) ยท 2.14 KB
/
DH_72413.java
File metadata and controls
92 lines (70 loc) ยท 2.14 KB
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
91
92
import java.util.*;
/*
* ํฉ์น ํ์ ์๊ธ
*/
class DH_72413 {
static class Node {
int e, c; // ๋์ฐฉ์ ๊ณผ ๋น์ฉ
public Node(int e, int c) {
this.e = e;
this.c = c;
}
}
static public int solution(int n, int s, int a, int b, int[][] fares) {
int answer = Integer.MAX_VALUE;
ArrayList<int[]>[] adj = initArrayList(n, fares);
int[] dis = dijkstra(adj, s); // ์์์ ์ผ๋ก๋ถํฐ ๊ฐ ๋
ธ๋๊น์ง์ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํจ
for(int i = 1; i < n + 1; i++) {
// i๊น์ง ๊ฐ๋๊ฒ ๊ณตํต๊ฑฐ๋ฆฌ, ๊ทธ๋ฆฌ๊ณ A, B ๊ฐ๊ฐ ์ง์ ๊ฐ์ผ ๋จ
int[] tmp = dijkstra(adj, i); // i์์๋ถํฐ A, B๊น์ง ๋๋ฌํ๋ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํจ
answer = Math.min(dis[i] + tmp[a] + tmp[b], answer);
}
return answer;
}
// s๋ก๋ถํฐ ๋ชจ๋ ๋
ธ๋๊น์ง ๊ฐ๋ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํจ
static int[] dijkstra(ArrayList<int[]>[] adj, int s) {
int[] dis = new int[adj.length];
boolean[] v = new boolean[adj.length];
Arrays.fill(dis, Integer.MAX_VALUE);
dis[0] = 0;
PriorityQueue<Node> q = new PriorityQueue<Node>(Comparator.comparingInt(o -> o.c));
q.add(new Node(s, 0));
dis[s] = 0;
while(!q.isEmpty()) {
Node current = q.poll();
if(v[current.e]) continue;
v[current.e] = true;
// System.out.println(">> " + current.c);
for(int[] next: adj[current.e]) {
if(dis[current.e] + next[1] < dis[next[0]]) {
dis[next[0]] = dis[current.e] + next[1];
q.add(new Node(next[0], dis[next[0]]));
}
}
}
return dis;
}
static ArrayList<int[]>[] initArrayList(int n, int[][] fares) {
ArrayList<int[]>[] adj = new ArrayList[n + 1];
for(int i = 0; i < n + 1; i++) {
adj[i] = new ArrayList<>();
}
for(int[] fare: fares) {
int a = fare[0];
int b = fare[1];
int c = fare[2];
adj[a].add(new int[] {b, c});
adj[b].add(new int[] {a, c});
}
return adj;
}
public static void main(String[] args) {
int n = 7;
int s = 3;
int a = 4;
int b = 1;
int[][] fares = {{5, 7, 9}, {4, 6, 4}, {3, 6, 1},
{3, 2, 3}, {2, 1, 6}};
System.out.println(solution(n, s, a, b, fares));
}
}