dijkstra算法最短路径c++
时间: 2023-12-22 10:28:40 浏览: 94
以下是使用C++实现Dijkstra算法求解最短路径的示例代码:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f; // 表示正无穷
struct Edge {
int to, w, cost;
Edge(int _to, int _w, int _cost) : to(_to), w(_w), cost(_cost) {}
};
vector<Edge> G[1005]; // 图的邻接表表示
int d[1005]; // 起点到各个点的最短距离
int c[1005]; // 起点到各个点的最小花费
bool vis[1005]; // 标记是否已经确定最短路径
void dijkstra(int s, int t) {
memset(d, INF, sizeof(d));
memset(c, INF, sizeof(c));
memset(vis, false, sizeof(vis));
d[s] = 0;
c[s] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push(make_pair(0, s));
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (vis[u]) continue;
vis[u] = true;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].to;
int w = G[u][i].w;
int cost = G[u][i].cost;
if (d[v] > d[u] + w) {
d[v] = d[u] + w;
c[v] = c[u] + cost;
pq.push(make_pair(d[v], v));
} else if (d[v] == d[u] + w && c[v] > c[u] + cost) {
c[v] = c[u] + cost;
}
}
}
cout << d[t] << " " << c[t] << endl;
}
int main() {
int n, m;
while (cin >> n >> m && n && m) {
for (int i = 1; i <= n; i++) {
G[i].clear();
}
for (int i = 0; i < m; i++) {
int u, v, w, cost;
cin >> u >> v >> w >> cost;
G[u].push_back(Edge(v, w, cost));
G[v].push_back(Edge(u, w, cost));
}
int s, t;
cin >> s >> t;
dijkstra(s, t);
}
return 0;
}
```
阅读全文