图论-最短路-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; }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析