From 4285c04a832b40bbe197a409005b8bd4ce4b80f9 Mon Sep 17 00:00:00 2001 From: JHLEE325 <82587652+JHLEE325@users.noreply.github.com> Date: Sun, 27 Jul 2025 12:35:16 +0900 Subject: [PATCH] =?UTF-8?q?[20250727]=20BOJ=20/=20G4=20/=20=ED=83=80?= =?UTF-8?q?=EC=9E=84=EB=A8=B8=EC=8B=A0=20/=20=EC=9D=B4=EC=A4=80=ED=9D=AC?= 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" | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 "JHLEE325/202507/27 BOJ G4 \355\203\200\354\236\204\353\250\270\354\213\240.md" diff --git "a/JHLEE325/202507/27 BOJ G4 \355\203\200\354\236\204\353\250\270\354\213\240.md" "b/JHLEE325/202507/27 BOJ G4 \355\203\200\354\236\204\353\250\270\354\213\240.md" new file mode 100644 index 00000000..7c593081 --- /dev/null +++ "b/JHLEE325/202507/27 BOJ G4 \355\203\200\354\236\204\353\250\270\354\213\240.md" @@ -0,0 +1,73 @@ +```java +import java.io.*; +import java.util.*; + +class Edge { + int from, to, cost; + + public Edge(int from, int to, int cost) { + this.from = from; + this.to = to; + this.cost = cost; + } +} + +public class Main { + static final long INF = 987654321; + static int n, m; + static List edges = new ArrayList<>(); + static long[] dist; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + + dist = new long[n + 1]; + + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + int from = Integer.parseInt(st.nextToken()); + int to = Integer.parseInt(st.nextToken()); + int cost = Integer.parseInt(st.nextToken()); + edges.add(new Edge(from, to, cost)); + } + + if (!bellmanFord(1)) { + System.out.println(-1); + } else { + for (int i = 2; i <= n; i++) { + if (dist[i] == INF) + System.out.println(-1); + else + System.out.println(dist[i]); + } + } + } + + static boolean bellmanFord(int start) { + Arrays.fill(dist, INF); + dist[start] = 0; + + for (int i = 1; i < n; i++) { + for (Edge e : edges) { + if (dist[e.from] != INF && dist[e.to] > dist[e.from] + e.cost) { + dist[e.to] = dist[e.from] + e.cost; + } + } + } + + for (Edge e : edges) { + if (dist[e.from] != INF && dist[e.to] > dist[e.from] + e.cost) { + return false; + } + } + + return true; + } +} + +```