Dijkstra
← 기록 / Graph

Dijkstra

Dijkstra 관련 기록.

이 글의 목차
  1. Dijkstra Algorithm
  2. Shortest Path Construction
  3. Time Complexity

Dijkstra Algorithm

  • adj[v] = {next, dist}
  • 음수 간선이 있으면 안됨.
int d[MAX_V], visited[MAX_V];
fill(d, d + MAX_V, INF);
fill(visited, visited + MAX_V, 0);
d[S] = 0;

priority_queue<pii> pq;
pq.push({0, S});

while(pq.size()) {
    auto cur = pq.top(); pq.pop();
    int v = cur.second;
    if (visited[v]) continue;
    visited[v] = 1;

    for(auto& t: adj[v]) {
        int newDist = -cur.first + t.second;
        if (newDist < d[t.first]) {
            d[t.first] = newDist;
            pq.push({-newDist, t.first});
        }
    }
}

Shortest Path Construction

int d[MAX_V], visited[MAX_V], pre[MAX_V];
fill(d, d + MAX_V, INF);
fill(pre, pre + MAX_V, -1);
fill(visited, visited + MAX_V, 0);
d[S] = 0;

priority_queue<pii> pq;
pq.push({0, S});

while(pq.size()) {
    auto cur = pq.top(); pq.pop();
    int v = cur.second;
    if (visited[v]) continue;
    visited[v] = 1;

    for(auto& t: adj[v]) {
        int newDist = -cur.first + t.second;
        if (newDist < d[t.first]) {
            d[t.first] = newDist;
            pre[t.first] = v;
            pq.push({-newDist, t.first});
        }
    }
}

vector<int> getPath(int t) {
    vector<int> res;
    for(int p = t; p != S; p = pre[p]) {
        res.push_back(p);
    }
    res.push_back(S);
    reverse(res.begin(), res.end());

    return res;
}

Time Complexity

  • O((V+E)log⁡V)O((V+E)\log V)
AI로 읽기 · Markdown

로그인 없이 읽는 Markdown 원문.

Markdown 열기 ↗
curl -fsSL 'https://www.readiz.com/notes/algorithm/graph/dijkstra/index.md'

서비스 열기

열기 방식을 선택해 주세요.

로그인이 필요하거나 창 안에서 열리지 않는 서비스는 현재 탭에서 열어 주세요.