题解(包AC)
2025-07-02 09:40:16
发布于:江苏
8阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 110;
const int INF = 0x3f3f3f3f;
vector<pair<int, int>> adj[MAXN]; // 邻接表:adj[u] 存储 {v, weight}
int dist[MAXN]; // 距离数组
void dijkstra(int start, int n) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
fill(dist, dist + n + 1, INF);
dist[start] = 0;
pq.push({0, start});
while (!pq.empty()) {
int d = pq.top().first;
int u = pq.top().second;
pq.pop();
if (d > dist[u]) continue; // 已经找到更短路径,跳过
for (auto &edge : adj[u]) {
int v = edge.first;
int w = edge.second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
adj[a].push_back({b, c});
adj[b].push_back({a, c}); // 无向图
}
dijkstra(1, n);
cout << dist[n] << endl;
return 0;
}
这里空空如也
有帮助,赞一个