
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static class Node implements Comparable<Node> {
int next;
int cost;
Node(int next, int cost) {
this.next = next;
this.cost = cost;
}
@Override
public int compareTo(Node o) {
return this.cost - o.cost;
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
int M = Integer.parseInt(br.readLine());
List<List<Node>> graph = new ArrayList<>();
for (int i = 0; i <= N; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < M; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int next = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
graph.get(start).add(new Node(next, cost));
}
StringTokenizer st = new StringTokenizer(br.readLine());
int startNode = Integer.parseInt(st.nextToken());
int endNode = Integer.parseInt(st.nextToken());
br.close();
boolean[] visited = new boolean[N + 1];
int[] cost = new int[N + 1];
Arrays.fill(cost, Integer.MAX_VALUE);
cost[startNode] = 0;
PriorityQueue<Node> queue = new PriorityQueue<>();
queue.add(new Node(startNode, cost[startNode]));
while (!queue.isEmpty()) {
Node cur = queue.poll();
int currentNode = cur.next;
if (visited[currentNode]) {
continue;
}
visited[currentNode] = true;
for (Node nextNode : graph.get(currentNode)) {
if (cost[nextNode.next] > cost[currentNode] + nextNode.cost) {
cost[nextNode.next] = cost[currentNode] + nextNode.cost; // update
queue.add(new Node(nextNode.next, cost[nextNode.next]));
}
}
}
bw.write(cost[endNode] + "\n");
bw.close();
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 9251번: LCS (0) | 2025.04.23 |
|---|---|
| [JAVA-자바] 2096번: 내려가기 (0) | 2025.04.20 |
| [JAVA-자바] 11660번: 구간 합 구하기 5 (0) | 2025.04.17 |
| [JAVA-자바] 9465번: 스티커 (0) | 2025.04.16 |
| [JAVA-자바] 1991번: 트리 순회 (0) | 2025.04.15 |