μκ³ λ¦¬μ¦/BOJ - Java
[BOJ/Java] 11404. νλ‘μ΄λ
ImJay
2025. 3. 10. 10:33
λ°μν
π [BOJ/Java] 11404. νλ‘μ΄λ
π‘ λ¬Έμ ν΄μ
Nκ°μ λμκ° μκ³ , Mκ°μ λ²μ€ λ
Έμ μ΄ μ‘΄μ¬νλ€.
κ° λ²μ€λ νΉμ ν λΉμ©μ΄ μμΌλ©°, λμ κ° μ΅λ¨ λΉμ©μ ꡬνλ λ¬Έμ μ΄λ€.
πΉ μ£Όμ΄μ§ μ 보
- N: λμμ κ°μ (2 ≤ N ≤ 100)
- M: λ²μ€ λ Έμ μ κ°μ (1 ≤ M ≤ 100,000)
- A B C: Aλ² λμμμ Bλ² λμλ‘ κ°λ λΉμ©μ΄ C (μ€λ³΅ κ°λ₯)
β
λͺ©ν:
1οΈβ£ λͺ¨λ λμ μ(i → j)μ λν μ΅μ λΉμ© κ²½λ‘λ₯Ό ꡬνκΈ°
2οΈβ£ κ²½λ‘κ° μλ κ²½μ° 0μ μΆλ ₯
π νμ΄ κ³Όμ
1οΈβ£ νλ‘μ΄λ-μμ μκ³ λ¦¬μ¦ μ¬μ©
- λͺ¨λ λ Έλμμ λͺ¨λ λ ΈλκΉμ§μ μ΅λ¨ 거리λ₯Ό ꡬνλ λ¬Έμ μ΄λ―λ‘ νλ‘μ΄λ-μμ μκ³ λ¦¬μ¦μ μ¬μ©
- μκ° λ³΅μ‘λ: O(N³), N=100μ΄λ―λ‘ μΆ©λΆν κ°λ₯
2οΈβ£ μ΄κΈ°ν
- 무νλ(INF) κ° μ€μ (dist[i][j] = INF)
- μκΈ° μμ μΌλ‘ κ°λ κ²½λ‘ dist[i][i] = 0
- μ λ ₯κ°μ λ°νμΌλ‘ μ§μ μ΄λ κ°λ₯ν 거리 μ€μ
3οΈβ£ νλ‘μ΄λ-μμ μν
- kλ² λ Έλλ₯Ό κ±°μ³κ°λ κ²½λ‘(i → k → j)λ₯Ό κ³ λ €νμ¬ i → jλ‘ κ°λ μ΅μ λΉμ© κ°±μ
π» μ½λ (Java)
import java.util.*;
public class Main {
static final int INF = 1000000000;
static int N, M;
static int[][] dist;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
dist = new int[N + 1][N + 1];
// 거리 λ°°μ΄ μ΄κΈ°ν
for (int i = 1; i <= N; i++) {
Arrays.fill(dist[i], INF);
dist[i][i] = 0; // μκΈ° μμ μ 0
}
// μ
λ ₯ λ°κΈ°
for (int i = 0; i < M; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
dist[a][b] = Math.min(dist[a][b], c); // κ°μ λ
Έμ μ΄ μ¬λ¬ κ°μΌ μ μμ
}
// νλ‘μ΄λ-μμ
μκ³ λ¦¬μ¦ μν
for (int k = 1; k <= N; k++) {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (dist[i][k] != INF && dist[k][j] != INF) {
dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
// κ²°κ³Ό μΆλ ₯
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
System.out.print((dist[i][j] == INF ? "0" : dist[i][j]) + " ");
}
System.out.println();
}
}
}
β± μκ° λ³΅μ‘λ λΆμ
- νλ‘μ΄λ-μμ μκ³ λ¦¬μ¦: O(N³), N ≤ 100μ΄λ―λ‘ 100³ = 1,000,000 μ°μ°μ μΆ©λΆν κ°λ₯
π§ λλ μ
β
νλ‘μ΄λ-μμ
μκ³ λ¦¬μ¦μ κΈ°λ³Έμ μΈ ννλ₯Ό μ΅ν μ μμλ€.
β
μ€λ³΅ κ°μ μ΄ μ‘΄μ¬ν μ μμΌλ―λ‘ Math.min()μΌλ‘ μ΅μ λΉμ© κ°±μ ν΄μΌ νλ€.
β
κ²½λ‘κ° μμ κ²½μ° 0μ μΆλ ₯νλ μ²λ¦¬λ₯Ό μ‘°μ¬ν΄μΌ νλ€.
π κ·Έλν μ΅λ¨ κ²½λ‘ λ¬Έμ μ κΈ°λ³Έ μ€ κΈ°λ³Έ! νμ€νκ² μ΅νμΌ ν λ¬Έμ λ€. π
λ°μν