Skip to content

Commit d1faba3

Browse files
authored
Merge pull request #645 from AlgorithmWithGod/LiiNi-coder
[20250810] BOJ / G4 / 운동 / 이인희
2 parents 5910afa + 68468ce commit d1faba3

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static class Edge {
7+
int to;
8+
int cost;
9+
Edge(int to, int cost) {
10+
this.to = to;
11+
this.cost = cost;
12+
}
13+
}
14+
15+
private static final int INF = 1_000_000_000;//플루이드워셜은 오버플로우 방지
16+
private static int V
17+
private static int E;
18+
private static ArrayList<Edge>[] graph;
19+
private static int[][] dist;
20+
21+
public static void main(String[] args) throws IOException {
22+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
23+
StringTokenizer st = new StringTokenizer(br.readLine());
24+
V = Integer.parseInt(st.nextToken());
25+
E = Integer.parseInt(st.nextToken());
26+
graph = new ArrayList[V + 1];
27+
for (int i = 1; i <= V; i++) {
28+
graph[i] = new ArrayList<>();
29+
}
30+
31+
dist = new int[V + 1][V + 1];
32+
for (int i = 1; i <= V; i++) {
33+
Arrays.fill(dist[i], INF);
34+
dist[i][i] = 0;
35+
}
36+
37+
for (int i = 0; i < E; i++) {
38+
st = new StringTokenizer(br.readLine());
39+
int a = Integer.parseInt(st.nextToken());
40+
int b = Integer.parseInt(st.nextToken());
41+
int c = Integer.parseInt(st.nextToken());
42+
graph[a].add(new Edge(b, c));
43+
dist[a][b] = c;
44+
}
45+
46+
//플로이드워셜진행
47+
for (int k = 1; k <= V; k++) {
48+
for (int i = 1; i <= V; i++) {
49+
for (int j = 1; j <= V; j++) {
50+
if (dist[i][j] > dist[i][k] + dist[k][j]) {
51+
dist[i][j] = dist[i][k] +dist[k][j];
52+
}
53+
}
54+
}
55+
}
56+
57+
//최소 사이클 찾기
58+
int answer = INF;
59+
for (int a = 1; a <= V; a++) {
60+
for (int b = 1; b <= V; b++) {
61+
if (a == b) continue;
62+
if (dist[a][b] != INF && dist[b][a] != INF) {
63+
answer = Math.min(answer, dist[a][b] + dist[b][a]);
64+
}
65+
}
66+
}
67+
68+
System.out.println((answer == INF)? -1 : answer);
69+
br.close();
70+
}
71+
}
72+
```

0 commit comments

Comments
 (0)