From 93524f9b0d808ef41046018e99667d3bea3a52fa Mon Sep 17 00:00:00 2001 From: Ukj0ng <90972240+Ukj0ng@users.noreply.github.com> Date: Wed, 17 Dec 2025 18:57:58 +0900 Subject: [PATCH] =?UTF-8?q?[20251217]=20BOJ=20/=20G4=20/=20=ED=83=80?= =?UTF-8?q?=EC=9E=84=EB=A8=B8=EC=8B=A0=20/=20=ED=95=9C=EC=A2=85=EC=9A=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...00\354\236\204\353\250\270\354\213\240.md" | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 "Ukj0ng/202512/17 BOJ G4 \355\203\200\354\236\204\353\250\270\354\213\240.md" diff --git "a/Ukj0ng/202512/17 BOJ G4 \355\203\200\354\236\204\353\250\270\354\213\240.md" "b/Ukj0ng/202512/17 BOJ G4 \355\203\200\354\236\204\353\250\270\354\213\240.md" new file mode 100644 index 00000000..b1efcb5e --- /dev/null +++ "b/Ukj0ng/202512/17 BOJ G4 \355\203\200\354\236\204\353\250\270\354\213\240.md" @@ -0,0 +1,67 @@ +``` +import java.io.*; +import java.util.*; + +public class Main { + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); + private static final long INF = (long)3e10 + 5; + private static List edges; + private static long[] dist; + private static int N, M; + + public static void main(String[] args) throws IOException { + init(); + boolean result = bellmanFord(); + + if (result) bw.write(-1 + "\n"); + else { + for (int i = 2; i <= N; i++) { + if (dist[i] != INF) bw.write(dist[i] + "\n"); + else bw.write(-1 + "\n"); + } + } + bw.flush(); + bw.close(); + br.close(); + } + + private static void init() throws IOException { + StringTokenizer st = new StringTokenizer(br.readLine()); + + N = Integer.parseInt(st.nextToken()); + M = Integer.parseInt(st.nextToken()); + edges = new ArrayList<>(); + dist = new long[N+1]; + + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + int A = Integer.parseInt(st.nextToken()); + int B = Integer.parseInt(st.nextToken()); + int C = Integer.parseInt(st.nextToken()); + edges.add(new int[]{A, B, C}); + } + } + + private static boolean bellmanFord() { + Arrays.fill(dist, INF); + dist[1] = 0; + + for (int i = 0; i < N-1; i++) { + for (int[] edge : edges) { + if (dist[edge[0]] != INF && dist[edge[1]] > dist[edge[0]] + edge[2]) { + dist[edge[1]] = dist[edge[0]] + edge[2]; + } + } + } + + for (int[] edge : edges) { + if (dist[edge[0]] != INF && dist[edge[1]] > dist[edge[0]] + edge[2]) { + return true; + } + } + + return false; + } +} +```