dijkstra - changicho/algorithm-training GitHub Wiki

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ•˜๋‚˜์˜ ์ •์ ์—์„œ ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ์œผ๋กœ ๊ฐ€๋Š” ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•

์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(E log_2(V))

์ดˆ๊ธฐํ™”

  1. ๊ฑฐ๋ฆฌ๋ฐฐ์—ด costs๋ฅผ ์ „๋ถ€ INF๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
  2. ์‹œ์ž‘์ ์˜ ๊ฑฐ๋ฆฌ๋ฅผ 0์œผ๋กœ ์ง€์ •ํ•œ๋‹ค (A -> A ์˜ ๊ฑฐ๋ฆฌ๋Š” 0์ด๋‹ค)
  3. ์šฐ์„ ์ˆœ์œ„ ํ pq๋ฅผ ์„ ์–ธํ•œ๋‹ค. (cost์— ์ตœ์†Œ๊ฐ’์ด ์ œ์ผ ์œ„์— ์˜ฌ๋ผ์™€์•ผํ•จ)
  4. pq์— ์‹œ์ž‘์ ์„ ์ €์žฅํ•œ๋‹ค.

while๋ฌธ (pq๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€)

  1. ํ˜„์žฌ ๋…ธ๋“œ์— pq์˜ top๊ฐ’์„ ํ• ๋‹นํ•˜๊ณ  pop
  2. ํ˜„์žฌ ๋…ธ๋“œ์— ์—ฐ๊ฒฐ๋œ ๊ฐ„์„ ์„ ํƒ์ƒ‰ํ•œ๋‹ค.
  3. ๊ฐ„์„ ์˜ ๋„์ฐฉ์ ๊นŒ์ง€ cost๋ฅผ ๋น„๊ตํ•œ๋‹ค (ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ์ง€๋‚˜์„œ ๊ฐ€๋Š” ๊ฒฝ์šฐ cost vs ์›๋ž˜ ๊ฐ„์„ ๊นŒ์ง€์˜ cost)
  4. ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ์ง€๋‚˜๊ฐ€๋Š” ๊ฒฝ์šฐ์˜ ๊ฐ€์ค‘์น˜ ํ•ฉ๊ณ„๊ฐ€ ๋” ์ž‘์œผ๋ฉด
    1. cost๋ฅผ ๊ฐฑ์‹ ํ•œ๋‹ค (costs ๋ฐฐ์—ด์˜ ๊ทธ๊ฒƒ์„ ๊ฐฑ์‹ ํ•œ๋‹ค)
    2. pq์— {cost, ๋„์ฐฉ์ }์„ pushํ•œ๋‹ค.
struct Edge {
  int to, cost;

  bool operator<(const Edge &b) const {
    return cost > b.cost; // ์šฐ์„ ์ˆœ์œ„ ํ์˜ top์ด ์ตœ์†Œ๊ฐ’์ด ๋˜๋„๋ก
  }
};

vector<vector<Edge>> graph;
vector<int> costs; // ์ฒ˜์Œ์— INFINITY๋กœ ์ดˆ๊ธฐํ™”ํ•ด์•ผํ•จ

void dijkstra(int start, vector<vector<Edge>> &graph, vector<int> &costs) {
  priority_queue<Edge> pq;

  fill(costs.begin(), costs.end(), INFINITY);

  pq.push({0, start, 0});
  while (!pq.empty()) {
    Edge cur = pq.top();
    pq.pop();

    for (Edge next : graph[cur.to]) {
      int new_val = costs[cur.to] + next.cost;
      int before_val = costs[next.to];

      if (new_val < before_val) {
        costs[next.to] = new_val;
        pq.push({next.to, new_val});
      }
    }
  }
}

pq๋ฅผ ์ตœ์†Œ ํž™์œผ๋กœ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•

priority_queue<pair<int,int> ,vector<pair<int,int> >,greater<pair<int,int> > pq;

// ์•„๋ž˜ header๋ฅผ ์ถ”๊ฐ€ํ•ด์„œ compareํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.
#include <functional>	// to use greater<>
greater<> // compare
โš ๏ธ **GitHub.com Fallback** โš ๏ธ