Skip to content

Commit 91f1352

Browse files
beberichetony9402
andauthored
[ADD] baekjoon 1507 java solution (#80)
* [ADD] baekjoon 1507 java solution * Refactoring --------- Co-authored-by: Minsang Kim <[email protected]>
1 parent 634cd0e commit 91f1352

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

solutions/baekjoon/1507/Main.java

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Authored by: beberiche
2+
// Co-authored by: -
3+
// Link: http://boj.kr/9b1dc9632bd749358f38832c1d34704a
4+
5+
import java.util.*;
6+
import java.io.*;
7+
8+
public class Main {
9+
public static void main(String[] args) {
10+
FastReader rd = new FastReader();
11+
int N = rd.nextInt();
12+
13+
int[][] a1 = new int[N][N];
14+
int[][] a2 = new int[N][N];
15+
16+
for (int i = 0; i < N; i++) {
17+
for (int j = 0; j < N; j++) {
18+
a1[i][j] = rd.nextInt();
19+
a2[i][j] = a1[i][j];
20+
}
21+
}
22+
23+
for (int k = 0; k < N; k++) {
24+
for (int i = 0; i < N; i++) {
25+
for (int j = 0; j < N; j++) {
26+
if (i == j || j == k || k == i) continue;
27+
28+
if (a1[i][j] > a1[i][k] + a1[k][j]) {
29+
System.out.println(-1);
30+
return;
31+
}
32+
33+
if (a1[i][j] == a1[i][k] + a1[k][j]) {
34+
a2[i][j] = 0;
35+
}
36+
}
37+
}
38+
}
39+
40+
int sum = 0;
41+
for (int i = 0; i < N; i++) {
42+
for (int j = i + 1; j < N; j++) {
43+
sum += a2[i][j];
44+
}
45+
}
46+
System.out.println(sum);
47+
}
48+
49+
static class FastReader {
50+
BufferedReader br;
51+
StringTokenizer st;
52+
53+
public FastReader() {
54+
br = new BufferedReader(new InputStreamReader(System.in));
55+
}
56+
57+
String next() {
58+
while (st == null || !st.hasMoreElements()) {
59+
try {
60+
st = new StringTokenizer(br.readLine());
61+
} catch (IOException e) {
62+
e.printStackTrace();
63+
}
64+
}
65+
return st.nextToken();
66+
}
67+
68+
int nextInt() {
69+
return Integer.parseInt(next());
70+
}
71+
72+
long nextLong() {
73+
return Long.parseLong(next());
74+
}
75+
76+
double nextDouble() {
77+
return Double.parseDouble(next());
78+
}
79+
80+
String nextLine() {
81+
String str = "";
82+
try {
83+
str = br.readLine();
84+
} catch (IOException e) {
85+
e.printStackTrace();
86+
}
87+
return str;
88+
}
89+
}
90+
}
91+
92+
/* Solution Description
93+
94+
1. 플로이드-워셜 응용 문제. 최단 경로의 결과가 입력 값으로 주어지고, 이를 기반으로 본래 사용된 간선을 확인한다.
95+
96+
2. 플로이드-워셜의 핵심은 현재 간선 비용보다 우회하여 오는 간선의 비용이 더 적은 경우 업데이트를 하는 것이다.
97+
따라서 우회한 간선의 합이 현재의 간선 비용과 동일하다면, 우회한 간선 쪽을 반영한 것이라고 추론할 수 있다.
98+
99+
3. 우회한 간선이 반영된 경우를 `0` 으로 변경하자.
100+
모든 탐색이 끝난 이후에도 `0` 이 아닌 간선이 본래 최단 경로를 결과를 찾기 위해 사용된 초기 간선이 된다.
101+
102+
4. 탐색 시, 현재 간선보다 우회한 간선의 합이 더 큰 경우,
103+
최단 경로를 잘못 파악한 것으로 간주하고 `-1` 을 출력한다.
104+
105+
*/

0 commit comments

Comments
 (0)