백준 11404번 플로이드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
 
const int MAX = 101;
 
int n, m;
int city[MAX][MAX];
int travel[MAX][MAX];
int Path[MAX][MAX];
 
 
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    
    cin >> n >> m;
    
    for (int i = 1; i <= m; i++) {
        int a, b,cost;
        cin >> a >> b >> cost;
        if (city[a][b] == 0)
            city[a][b] = cost;
        else
            city[a][b] = min(city[a][b], cost);
    }
    for(int k=1;k<=n;k++)
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                //경로가 둘중 하나라도 없는경우, 자기가 자신한테 가는경우 모두 제외
                if (city[i][k]==0||city[k][j] == 0 || i == j)
                    continue;
                //직선으로 가는 경우가 없는경우,우회해서 가는게 더 빠른경우 갱신
                if (city[i][j]==0||city[i][j] > city[i][k] + city[k][j]) {
                    city[i][j] = city[i][k] + city[k][j];
                    Path[i][j] = k;
                }
            }
        }
 
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++)
            cout << city[i][j] << " ";
        cout << endl;
    }
 
    return 0;
}
 
cs

출처:https://www.acmicpc.net/problem/11404


플로이드의 최단경로 알고리즘을 사용하는 문제였습니다. 

city[i][j]==0인 경우가 최소값으로 들어가는게 아니라 길이 없다는 예외처리를 해주는 것에 신경을 쓰면 풀 수 있는 문제였습니다. 


'알고리즘 > BAEKJOON' 카테고리의 다른 글

백준 13700번 완전 범죄  (0) 2019.03.26
백준 11780번 플로이드2  (0) 2019.03.26
백준 15325번 Doktor  (0) 2019.03.25
백준 16719번 ZOAC  (0) 2019.03.25
백준 1158번 조세퍼스 문제  (0) 2019.03.24

+ Recent posts