dijkstra解决无负权边的图的最短路,有向无向都可以,密集图无需优先队列优化,直接利用d数组遍历找最小值即可。
const int INF = 0x3fffffff;
struct Edge{
int to, cost;
Edge(int nto, int ncost) : to(nto),cost(ncost){}
Edge(){};
bool operator < (const Edge& rhs) const{
return cost > rhs.cost;
}
};
vector<vector<Edge> > G;
priority_queue<Edge> pq;
int d[30010], n;
//d保存着每个点到源点的最短距离。
int dijkstra(int head, int tail){
while(!pq.empty())
pq.pop();
fill(d+1, d+n+1, INF);
pq.push(Edge(head, 0));
d[head] = 0;
Edge t;
while(!pq.empty()){
t = pq.top(); pq.pop();
if(t.to == tail)
break;
if(d[t.to] < t.cost)//判断t是否已经有近的路或者已经访问过
continue;
for(int i = 0; i < G[t.to].size(); ++i){
Edge e = G[t.to][i];
if(d[e.to] > t.cost + e.cost) {//只将需要更新的节点加入队列
d[e.to] = t.cost + e.cost;
pq.push(Edge(e.to, d[e.to]));
}
}
}
return t.cost;
}