C++Dijkstra代码
时间: 2023-11-14 17:15:10 浏览: 98
以下是Dijkstra算法的C++代码:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <functional>
using namespace std;
typedef pair<int, int> PII;
const int INF = 1e9;
const int MAXN = 1000;
vector<PII> adj[MAXN]; // 存储邻接表
int dijkstra(int s, int t) {
priority_queue<PII, vector<PII>, greater<PII>> pq;
vector<int> dist(MAXN, INF); // 存储到各个点的距离
dist[s] = 0;
pq.push({dist[s], s});
while (!pq.empty()) {
PII p = pq.top();
pq.pop();
int d = p.first;
int u = p.second;
if (dist[u] < d) continue;
for (auto& e : adj[u]) {
int v = e.first;
int w = e.second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
return dist[t];
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
int s, t;
cin >> s >> t;
cout << dijkstra(s, t) << endl;
return 0;
}
```
阅读全文