Skip to content

Commit 161937a

Browse files
committedMay 27, 2024
BOJ_11657 : 타임머신 (벨만 포드)
1 parent 15c99dc commit 161937a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
 

Diff for: ‎week7/BOJ_11657(타임머신).java

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
public class Main {
5+
6+
public static int city;
7+
public static List<List<int[]>> graph;
8+
public static long[] dist;
9+
10+
public static void main(String[] args) throws IOException {
11+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12+
StringTokenizer st = new StringTokenizer(br.readLine());
13+
city = Integer.parseInt(st.nextToken());
14+
int bus = Integer.parseInt(st.nextToken());
15+
graph = new ArrayList<>();
16+
dist = new long[city+1];
17+
for(int i=0; i<=city; i++) {
18+
graph.add(new ArrayList<>());
19+
dist[i] = Long.MAX_VALUE;
20+
}
21+
for(int i=0; i<bus; i++) {
22+
st = new StringTokenizer(br.readLine());
23+
int v1 = Integer.parseInt(st.nextToken());
24+
int v2 = Integer.parseInt(st.nextToken());
25+
int cost = Integer.parseInt(st.nextToken());
26+
graph.get(v1).add(new int[]{v2, cost});
27+
}
28+
bellmanFord(1);
29+
}
30+
31+
public static void bellmanFord(int start) {
32+
dist[start] = 0;
33+
for(int i=1; i<=city; i++) {
34+
for(int j=1; j<=city; j++) {
35+
List<int[]> list = graph.get(j);
36+
for(int k=0; k<list.size(); k++) {
37+
int nextV = list.get(k)[0];
38+
int nextCost = list.get(k)[1];
39+
if(dist[j] != Long.MAX_VALUE && dist[nextV] > dist[j] + nextCost) {
40+
dist[nextV] = dist[j] + nextCost;
41+
42+
// city(정점 개수)번째 반복에 갱신되는 값이 있으면 음수 사이클 존재
43+
if(i == city) {
44+
System.out.println("-1");
45+
return;
46+
}
47+
}
48+
}
49+
}
50+
}
51+
for(int i=2; i<=city; i++) {
52+
System.out.println((dist[i] == Long.MAX_VALUE) ? "-1" : dist[i]);
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)