ย - Last update: 2023-08-07

Shortest Path Faster Algorithm

  • adj[v] = {next, dist}
  • ์Œ์ˆ˜ ๊ฐ„์„ ์ด ์žˆ์–ด๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
    • ์‚ฌ์ดํด์„ ์žก๊ธฐ ์œ„ํ•ด์„œ ๊ฐ ์ •์ ์˜ ๋ฐฉ๋ฌธ ์ˆ˜๋ฅผ ์ฒดํฌํ•ด์„œ MAX_V๋ณด๋‹ค ์ปค์ง€๋ฉด ํƒˆ์ถœํ•œ๋‹ค.
  • ํ‰๊ท ์ ์œผ๋กœ ์ˆ˜ํ–‰ ์‹œ๊ฐ„์ด ๋น ๋ฅธ ์•Œ๊ณ ๋ฆฌ์ฆ˜
int d[MAX_V], inQ[MAX_V];
fill(d, d + MAX_V, INF);
fill(inQ, inQ + MAX_V, 0);
d[S] = 0;
inQ[S] = 1;
queue<int> q;
q.push(S);
while(q.size()) {
auto cur = q.top(); q.pop();
inQ[cur] = 0;
// Check Negative Loop here if you want
// if (++cnt[cur] >= MAX_V || d[cur] < -INF) ~
for(auto& t: adj[cur]) {
int newDist = d[cur] + t.second;
if (newDist < d[t.first]) {
d[t.first] = newDist;
if (inQ[t.first] == 0) {
q.push(t.first);
inQ[t.first] = 1;
}
}
}
}

Shortest Path Construction

int d[MAX_V], inQ[MAX_V], pre[MAX_V];
fill(d, d + MAX_V, INF);
fill(inQ, inQ + MAX_V, 0);
fill(pre, pre + MAX_V, -1);
d[S] = 0;
inQ[S] = 1;
queue<int> q;
q.push(S);
while(q.size()) {
auto cur = q.top(); q.pop();
inQ[cur] = 0;
// Check Negative Loop here if you want
// if (++cnt[cur] >= MAX_V || d[cur] < -INF) ~
for(auto& t: adj[cur]) {
int newDist = d[cur] + t.second;
if (newDist < d[t.first]) {
d[t.first] = newDist;
pre[t.first] = cur;
if (inQ[t.first] == 0) {
q.push(t.first);
inQ[t.first] = 1;
}
}
}
}
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

  • Worst: O(VE)O(VE)
  • Best: O(V+E)O(V + E)