圖論-最短路-dijkstra演算法
阿新 • • 發佈:2019-01-01
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;
}