Algorithm/Baekjoon
[Algorithm/Baekjoon] ํํฐ - 1238 (G3/JAVA)
dpdms2148
2023. 6. 22. 23:30
728x90
๐๋ฌธ์ ๋งํฌ
๐ป์ฝ๋
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int X = Integer.parseInt(st.nextToken());
ArrayList<int[]>[] cost = new ArrayList[N + 1];
ArrayList<int[]>[] reversCost = new ArrayList[N + 1];
for (int i = 1; i < N + 1; i++) {
cost[i] = new ArrayList<>();
reversCost[i] = new ArrayList<>();
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
int time = Integer.parseInt(st.nextToken());
cost[start].add(new int[]{end, time});
reversCost[end].add(new int[]{start, time});
}
int[] timeSum = dijkstra(X, N, cost);
int[] reversTimeSum = dijkstra(X, N, reversCost);
int answer = 0;
for (int i = 1; i < N + 1; i++) {
answer = Math.max(answer, timeSum[i] + reversTimeSum[i]);
}
System.out.println(answer);
}
private static int[] dijkstra(int x, int n, ArrayList<int[]>[] cost) {
int[] time = new int[n + 1];
Arrays.fill(time, 1000000);
// ์ต๋จ ์๊ฐ๋ฅผ ๊ฐ์ง๋ ๋
ธ๋๋ฅผ ์์ ๋ฐฐ์น
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[1]));
// ์ถ๋ฐ ๋
ธ๋๋ฅผ x๋ก ํ๊ณ ๊ฑฐ๋ฆฌ๋ฅผ 0์ผ๋ก ์ด๊ธฐํ
pq.add(new int[]{x, 0});
while (!pq.isEmpty()) {
int[] cur = pq.poll();
// ์ต์๊ฐ์ด ์
๋ฐ์ดํธ ๋๋ ๋
ธ๋๋ง ํ์
if (time[cur[0]] < cur[1]) continue;
time[cur[0]] = cur[1];
// ์ธ์ ๋
ธ๋ ์กฐ์ฌ
for (int[] c : cost[cur[0]]) {
pq.add(new int[]{c[0], cur[1] + c[1]});
}
}
return time;
}
}
//์ฐธ๊ณ : https://girawhale.tistory.com/43
โณํ๊ณ
- ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ํ์ฉํด์ ํ์ดํ๊ณ , ์ฐ์ ์์ํ๋ฅผ ํ์ฉํด์ ์๊ฐ์ด ๊ฐ์ฅ ์์ ๊ฒฝ์ฐ๋ง ํ์ํ๊ธฐ ์ํด์ ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ๋ค.
- ๊ทธ๋ํ ํ์์ ๋ํด์ ๊ณต๋ถ ํด์ผ๊ฒ ๋ค.
728x90