Skip to content

Commit 9aa3f9f

Browse files
authored
Merge pull request #59 from AlgorithmWithGod/lkhyun
[20250206] BOJ / 실버1 / 지름길 / 이강현
2 parents 8c8ff8e + 36f555d commit 9aa3f9f

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
class Node implements Comparable<Node> {
6+
int vertex, weight;
7+
8+
Node(int vertex, int weight) {
9+
this.vertex = vertex;
10+
this.weight = weight;
11+
}
12+
13+
@Override
14+
public int compareTo(Node n) {
15+
return this.weight - n.weight;
16+
}
17+
}
18+
19+
public class Main {
20+
final static int INF = Integer.MAX_VALUE;
21+
static List<Node>[] graph;
22+
static int[] dist;
23+
24+
public static void dijkstra(int start, int D) {
25+
PriorityQueue<Node> minheap = new PriorityQueue<>();
26+
Arrays.fill(dist, INF); // 거리 초기화
27+
dist[start] = 0;
28+
minheap.add(new Node(start, 0));
29+
30+
while (!minheap.isEmpty()) {
31+
Node current = minheap.poll();
32+
33+
if (current.weight > dist[current.vertex]) continue;
34+
35+
for (Node next : graph[current.vertex]) {
36+
int newWeight = dist[current.vertex] + next.weight;
37+
if (dist[next.vertex] > newWeight) {
38+
dist[next.vertex] = newWeight;
39+
minheap.add(new Node(next.vertex, newWeight));
40+
}
41+
}
42+
}
43+
}
44+
45+
public static void main(String[] args) throws Exception {
46+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
47+
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
48+
StringTokenizer st = new StringTokenizer(br.readLine());
49+
int N = Integer.parseInt(st.nextToken());
50+
int D = Integer.parseInt(st.nextToken());
51+
52+
graph = new ArrayList[D + 1];
53+
dist = new int[D + 1];
54+
for (int i = 0; i <= D; i++) {
55+
graph[i] = new ArrayList<>();
56+
}
57+
58+
for (int i = 0; i < N; i++) {
59+
st = new StringTokenizer(br.readLine());
60+
int start = Integer.parseInt(st.nextToken());
61+
int end = Integer.parseInt(st.nextToken());
62+
int weight = Integer.parseInt(st.nextToken());
63+
64+
if (end <= D && (end - start) > weight) { // 일방통행이니까 목적지보다 더 가거나 굳이 탈 이유가 없는 지름길 제외
65+
graph[start].add(new Node(end, weight));
66+
}
67+
}
68+
for (int i = 0; i < D; i++) { //지름길 안타는 경우우
69+
graph[i].add(new Node(i + 1, 1));
70+
}
71+
72+
// 다익스트라 실행
73+
dijkstra(0, D);
74+
75+
// 최단 거리 출력
76+
bw.write(dist[D] + "\n");
77+
bw.flush();
78+
bw.close();
79+
}
80+
}
81+
82+
```

0 commit comments

Comments
 (0)