ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Dijkstra
    Algorithm/그래프 2020. 1. 15. 04:06
    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
    //다익스트라의 최단 거리 알고리즘의 구현
     
    //정점의 개수
    int V;
    //그래프의 인접 리스트, (연결된 정점 번호, 간선 가중치) 쌍을 담는다.
    vector<pair<intint>> adj[MAX_V];
    vector<int> dijkstra(int src)
    {
        vector<int> dist(V, INF);
        dist[src] = 0;
        priority_queue<pair<intint>> pq;
        pq.push(make_pair(0, src));
        while(!pq.empty())
        {
            int cost = -pq.top().first;
            int here = pq.top().second;
            pq.pop();
            //만약 지금 꺼낸 것보다 더 짧은 경로를 알고 있다면 지금 꺼낸 것을 무시한다.
            if(dist[here] < cost) continue;
            //인접한 정점들을 모두 검사한다.
            for(int i = 0; i<adj[here].size(); ++i)
            {
                int there = adj[here][i].first;
                int nextDist = cost + adj[here][i].second;
                //더 짧은 경로를 발견하면, dist[]를 갱신하고 우선순위 큐에 넣는다.
                if(int i = 0; i<adj[here].size(); ++i)
                {
                    int there = adj[here][i].first;
                    int nextDist = cost + adj[here][i].second;
                    //더 짧은 경로를 발견하면, dist[]를 갱신하고 우선순위 큐에 넣는다.
                    if(dist[there] > nextDist)
                    {
                        dist[there] = nextDist;
                        pq.push(make_pair(-nextDist, there));
                    }
                }
            }
        }
        return dist;
    }
    cs
     

     

    Dijkstra algorithm

    단일 시작점 최단 경로 알고리즘

    시작 정점에서부터 다른 정점까지들의 최단 거리를 계산합니다.

    음수 싸이클이 있으면 사용불가!

     

    시간복잡도

    O(|E|lg|v|)

     

     

     

     

     

    프로그래밍 대회에서 배우는 알고리즘 문제해결전략2

     

    'Algorithm > 그래프' 카테고리의 다른 글

    Floyd-Warshall algorithm  (0) 2020.01.23
    Bellman-Ford algorithm  (0) 2020.01.20
    tarjan's SCC algorithm  (0) 2020.01.20
    BFS  (0) 2020.01.10
    DFS  (0) 2020.01.10

    댓글

Designed by Tistory.