dijkstra - changicho/algorithm-training GitHub Wiki
ํ๋์ ์ ์ ์์ ๋ค๋ฅธ ๋ชจ๋ ์ ์ ์ผ๋ก ๊ฐ๋ ์ต๋จ ๊ฒฝ๋ก๋ฅผ ๊ตฌํ๋ ๋ฐฉ๋ฒ
์๊ฐ ๋ณต์ก๋๋ O(E log_2(V))
์ด๊ธฐํ
- ๊ฑฐ๋ฆฌ๋ฐฐ์ด costs๋ฅผ ์ ๋ถ INF๋ก ์ด๊ธฐํํ๋ค.
- ์์์ ์ ๊ฑฐ๋ฆฌ๋ฅผ 0์ผ๋ก ์ง์ ํ๋ค (A -> A ์ ๊ฑฐ๋ฆฌ๋ 0์ด๋ค)
- ์ฐ์ ์์ ํ pq๋ฅผ ์ ์ธํ๋ค. (cost์ ์ต์๊ฐ์ด ์ ์ผ ์์ ์ฌ๋ผ์์ผํจ)
- pq์ ์์์ ์ ์ ์ฅํ๋ค.
while๋ฌธ (pq๊ฐ ๋น ๋๊น์ง)
- ํ์ฌ ๋ ธ๋์ pq์ top๊ฐ์ ํ ๋นํ๊ณ pop
- ํ์ฌ ๋ ธ๋์ ์ฐ๊ฒฐ๋ ๊ฐ์ ์ ํ์ํ๋ค.
- ๊ฐ์ ์ ๋์ฐฉ์ ๊น์ง cost๋ฅผ ๋น๊ตํ๋ค (ํ์ฌ ๋ ธ๋๋ฅผ ์ง๋์ ๊ฐ๋ ๊ฒฝ์ฐ cost vs ์๋ ๊ฐ์ ๊น์ง์ cost)
- ํ์ฌ ๋
ธ๋๋ฅผ ์ง๋๊ฐ๋ ๊ฒฝ์ฐ์ ๊ฐ์ค์น ํฉ๊ณ๊ฐ ๋ ์์ผ๋ฉด
- cost๋ฅผ ๊ฐฑ์ ํ๋ค (costs ๋ฐฐ์ด์ ๊ทธ๊ฒ์ ๊ฐฑ์ ํ๋ค)
- 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