백준 11780 플로이드2

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#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 Count;
 
void route(int i, int j) {
    if (Path[i][j] != 0) {
        route(i, Path[i][j]);
        cout << Path[i][j] << " ";
        route(Path[i][j], j);
    }
}
 
void Findcost(int i, int j) {
    if (Path[i][j] != 0) {
        Count++;
        Findcost(i, Path[i][j]);
        Findcost(Path[i][j], j);
    }
}
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;
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (city[i][j] == 0) {
                cout << 0 << endl;
            }
            else {
                //시작,끝은 무조건 지나므로 2개 시작
                Count = 2;
                //도시 몇번지나는지 카운터해주기
                Findcost(i, j);
                cout << Count<< " " << i<<" ";
                route(i,j);
                cout << j<<endl;
 
            }
        }
    }
    return 0;
}
 
cs

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


Path[i][j]에 경로 k를 넣은뒤 재귀를 이용해서 route.Findcost함수를 작성하는게 포인트였습니다.

Findcost함수의 Count++의 위치는 전,중,후 아무곳이나 상관없이 카운트를 할 수 있습니다. 


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

백준 11049번 행렬 곱셈 순서  (0) 2019.03.27
백준 13700번 완전 범죄  (0) 2019.03.26
백준 11404번 플로이드  (0) 2019.03.26
백준 15325번 Doktor  (0) 2019.03.25
백준 16719번 ZOAC  (0) 2019.03.25

+ Recent posts