
소스코드:
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 int N, M, X;
static List<List<Node>> graph;
static List<List<Node>> graph_reverse;
public static class Node {
int to;
int cost;
Node(int t, int c) {
this.to = t;
this.cost = c;
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
X = Integer.parseInt(st.nextToken());
graph = new ArrayList<>();
graph_reverse = new ArrayList<>();
for (int i = 0; i <= N; i++) {
graph.add(new ArrayList<>());
graph_reverse.add(new ArrayList<>());
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
graph.get(start).add(new Node(to, cost));
graph_reverse.get(to).add(new Node(start, cost));
}
br.close();
int[] gogo = dijkstra(X, graph_reverse);
int[] back = dijkstra(X, graph);
int result = 0;
for (int i = 1; i <= N; i++) {
int calc = gogo[i] + back[i];
result = Math.max(result, calc);
}
bw.write(result + "\n");
bw.close();
}
public static int[] dijkstra(int start, List<List<Node>> g) {
int[] distance = new int[N + 1];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[start] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>(((o1, o2) -> o1[1] - o2[1]));
pq.add(new int[]{start, distance[start]});
while (!pq.isEmpty()) {
int[] cur = pq.poll();
int cur_node = cur[0];
int cur_distance = cur[1];
if (cur_distance > distance[cur_node]) {
continue;
}
for (Node near : g.get(cur_node)) {
int next = near.to;
int cost = near.cost;
if (distance[next] > distance[cur_node] + cost) {
distance[next] = distance[cur_node] + cost;
pq.add(new int[]{next, distance[next]});
}
}
}
return distance;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 2206번: 벽 부수고 이동하기 (0) | 2025.05.22 |
|---|---|
| [JAVA-자바] 1865번: 웜홀 (0) | 2025.05.21 |
| [JAVA-자바] 17144번: 미세먼지 안녕! (0) | 2025.05.18 |
| [JAVA-자바] 14938번: 서강그라운드 (0) | 2025.05.16 |
| [JAVA-자바] 14502번: 연구소 (0) | 2025.05.15 |