您的位置:首页 > 其它

图论-最短路-dijkstra算法

2016-05-09 12:29 253 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 dijkstra