ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 최단 경로
    백준알고리즘 2019. 9. 29. 00:16

    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
    #include<iostream>
    #include<vector>
    #include<queue>
    #include<utility>
     
    using namespace std;
    class PAIR {
    public:
        int x, y;
        PAIR(int x, int y) {
            this->= x;
            this->= y;
     
        }
    };
    int tc,n, d, c;
    vector<PAIR> map[20000];
    int visit[20000];
    //bool dist[20000];
    int node, edge;
    int INF = 987654321;
    int dist[20000];
     
     
    void dijkstra(int start) {
        visit[start] = 0;
        priority_queue<pair<intint> > pq;
        pq.push(make_pair(0,start));
        while (!pq.empty()) {
            int current = pq.top().second;
            int distance = -pq.top().first;
            pq.pop();
            //if (visit[current] < distance) continue;
            for(int i = 0; i< map[current].size(); i++){
                int next = visit[current] + map[current][i].y;
                int before = visit[map[current][i].x];
                if (next < before) {
                    visit[map[current][i].x] = next;
                    pq.push(make_pair-next,map[current][i].x));
                }
            }
        }
     
    }
     
    int main() {
        ios_base::sync_with_stdio(0);
        cin.tie(0);
        cin >> node >> edge;
        int start;
        cin >> start;
        for (int i = 0; i < node; i++) {
            visit[i] = INF;
        }
        for (int i = 0; i < edge; i++) {
            int a, b, c;
            cin >> a >> b >> c;
            map[a - 1].push_back(PAIR(b-1,c));
            //map[b - 1].push_back({ a - 1,c });
     
        }
        
        dijkstra(start-1);
        for (int i = 0; i < node; i++) {
            if (visit[i] != INF)
                cout << visit[i] << '\n';
            else
                cout << "INF" << '\n';
        }
        return 0;
    }
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

    마찬가지로 다익스트라 알고리즘이다.

    주의해야할게, 경로의 가치의 크기에 따른 우선순위 큐이기때문에, first와 second의 위치가 바뀌어야한다

     

    '백준알고리즘' 카테고리의 다른 글

    네트워크 연결  (0) 2019.09.29
    최소비용 구하기  (0) 2019.09.29
    해킹  (0) 2019.09.28
    최소 스패닝 트리  (0) 2019.09.27
    통나무 옮기기  (0) 2019.09.27

    댓글

Designed by Tistory.