Toolbox: Dijkstra's
Toolbox: Dijkstra's Shortest Path Algorithm
What is it?
Dijkstra's is a shortest path algorithm especially optimized for sparse graphs.
Code?
Optimized (+ priority queue - needs <queue>)
struct value
{
int dat, val; constexpr bool operator<( const value& rhs) const { return val > rhs.val; }
};
priority_queue<value> pq;
vector<value> elist[805];
void dj(int st)
{
memset(tmp, 63, sizeof tmp);
tmp[st] = 0;
pq.push({st, 0});
while(!pq.empty())
{
value u = pq.top(); pq.pop();
if(tmp[u.dat] != u.val) continue;
for(value x:elist[u.dat]) // if C++11 incomaptible, change
{
int alt = u.val + x.val;
if(alt < tmp[x.dat]) { tmp[x.dat] = alt; pq.push({x.dat, alt}); }
}
}
}
Explanation?
Dependencies
- <vector>, <queue>
- C++ 11 or above
- st, starting point
- Edge list in elist
Outputs
- tmp, array of distances between starting point and any point
Comments
Post a Comment