AcWing 850. Dijkstra求最短路 II C++
原题链接
简单
作者:
LaChimere
,
2021-05-28 15:38:02
,
所有人可见
,
阅读 284
C++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXSIZE = 150010;
const int INF = 0x3f3f3f3f;
int n, m;
vector<vector<pair<int, int> > > graph(MAXSIZE, vector<pair<int, int> >());
vector<bool> visited(MAXSIZE, false);
vector<int> dist(MAXSIZE, INF);
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
void addEdge(int from, int to, int weight) {
graph[from].emplace_back(weight, to);
}
void dijkstra(int start) {
dist[start] = 0;
pq.emplace(dist[start], start);
while (!pq.empty()) {
auto [d, v] = pq.top();
pq.pop();
if (visited[v]) {
continue;
}
visited[v] = true;
for (const auto [w, u] : graph[v]) {
if (!visited[u] && d + w < dist[u]) {
dist[u] = d + w;
pq.emplace(dist[u], u);
}
}
}
}
void init() {
int x, y, z;
cin >> n >> m;
while (m--) {
cin >> x >> y >> z;
addEdge(x, y, z);
}
}
int main() {
init();
dijkstra(1);
if (dist[n] == INF) {
cout << -1 << endl;
} else {
cout << dist[n] << endl;
}
return 0;
}