图论-最短路-dijkstra算法

来源:互联网 发布:python运算符优先级 编辑:程序博客网 时间:2024/05/02 03:09

dijkstra算法的思想是每次找出目前最短路径的点,然后再找下一个最短的点。可以利用堆优化降低复杂度。

缺点:不能处理负边。

#include <iostream>#include <algorithm>#include <vector>#include <queue>using namespace std;const int INF = 1e9 + 7;const int MAX_V = 100;const int MAX_E = 100;//int cost[MAX_V][MAX_V];//int d[MAX_V];//bool used[MAX_V];//int V;////void dijkstra(int s) {//  fill(d, d+V, INF);//  fill(used, used + V, false);//  d[s] = 0;//  //  while (true) {//      int v = -1;//      for (int u = 0; u < V; u++) {//          if (!used[u] && (v == -1 || d[u] < d[v])) v = u;//      }//      //      if (v == -1) break;//      used[v] = true;//      //      for (int u = 0; u < V; u++) {//          d[u] = min(d[u], d[v] + cost[v][u]);//      }//  }//}//用优先队列优化struct edge { int to, cost; };typedef pair<int, int> P; // first是最短距离,second是顶点的编号int V;vector<edge> G[MAX_V];int d[MAX_V];void dijkstra(int s) {    priority_queue<P, vector<P>, greater<P> > que;    fill(d, d+V, INF);    d[s] = 0;    que.push(P(0, s));    while (!que.empty()) {        P p = que.top(); que.pop();        int v = p.second;        if (d[v] < p.first) continue;        for (int i = 0; i < G[v].size(); i++) {            edge e = G[v][i];            if (d[e.to] > d[v] + e.cost) {                d[e.to] = d[v] + e.cost;                que.push(P(d[e.to], e.to));            }        }    }}int main() {    return 0;}
0 0