ย - 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;
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;
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)
- Best: O(V+E)