| 123456789101112131415161718192021222324252627282930313233343536373839 |
- #include <functional>
- #include <iostream>
- #include <limits>
- #include <queue>
- #include <utility>
- #include <vector>
- using namespace std;
- struct Edge { int to; long long weight; };
- int main() {
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- int n, m; cin >> n >> m;
- vector<vector<Edge>> g(n);
- while (m--) {
- int u, v; long long w; cin >> u >> v >> w; --u; --v;
- g[u].push_back({v, w}); g[v].push_back({u, w});
- }
- const long long inf = numeric_limits<long long>::max() / 4;
- vector<long long> first(n, inf), second(n, inf);
- priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;
- first[0] = 0; pq.push({0, 0});
- while (!pq.empty()) {
- auto [d, u] = pq.top(); pq.pop();
- if (d > second[u]) continue;
- for (Edge e : g[u]) {
- long long candidate = d + e.weight;
- if (candidate < first[e.to]) {
- swap(candidate, first[e.to]);
- pq.push({first[e.to], e.to});
- }
- if (first[e.to] < candidate && candidate < second[e.to]) {
- second[e.to] = candidate;
- pq.push({second[e.to], e.to});
- }
- }
- }
- cout << second[n - 1] << '\n';
- }
|