
소스코드:
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 {
public static class Node {
int to;
int cost;
Node(int t, int c) {
this.to = t;
this.cost = c;
}
}
static BufferedReader br;
static BufferedWriter bw;
static List<List<Node>> nodeList;
static int N, E, U, V;
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());
E = Integer.parseInt(st.nextToken());
nodeList = new ArrayList<>();
for (int i = 0; i <= N; i++) {
nodeList.add(new ArrayList<>());
}
for (int i = 0; i < E; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
nodeList.get(start).add(new Node(to, cost));
nodeList.get(to).add(new Node(start, cost));
}
st = new StringTokenizer(br.readLine());
U = Integer.parseInt(st.nextToken());
V = Integer.parseInt(st.nextToken());
br.close();
int[] from1 = dijkstra(1, N);
int[] fromU = dijkstra(U, N);
int[] fromV = dijkstra(V, N);
int U_V_N;
if (from1[U] == Integer.MAX_VALUE || fromU[V] == Integer.MAX_VALUE || fromV[N] == Integer.MAX_VALUE) {
U_V_N = -1;
} else {
U_V_N = from1[U] + fromU[V] + fromV[N];
}
int V_U_N;
if (from1[V] == Integer.MAX_VALUE || fromV[U] == Integer.MAX_VALUE || fromU[N] == Integer.MAX_VALUE) {
V_U_N = -1;
} else {
V_U_N = from1[V] + fromV[U] + fromU[N];
}
int result;
if (U_V_N == -1 && V_U_N == -1) {
result = -1;
} else if (U_V_N == -1) {
result = V_U_N;
} else if (V_U_N == -1) {
result = U_V_N;
} else {
result = Math.min(U_V_N, V_U_N);
}
bw.write(result + "\n");
bw.close();
}
public static int[] dijkstra(int start, int to) {
int[] distance = new int[N + 1];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[start] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> o1.cost - o2.cost);
pq.add(new Node(start, 0));
while (!pq.isEmpty()) {
Node current = pq.poll();
if (current.cost > distance[current.to]) {
continue;
}
for (Node next : nodeList.get(current.to)) {
if (distance[next.to] > current.cost + next.cost) {
distance[next.to] = current.cost + next.cost;
pq.add(new Node(next.to, distance[next.to]));
}
}
}
return distance;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 1967번: 트리의 지름 (0) | 2025.05.03 |
|---|---|
| [JAVA-자바] 1753번: 최단경로 (0) | 2025.05.02 |
| [JAVA-자바] 1043번: 거짓말 (0) | 2025.04.30 |
| [JAVA-자바] 17070번: 파이프 옮기기 1 (0) | 2025.04.29 |
| [JAVA-자바] 15686번: 치킨 배달 (0) | 2025.04.25 |