POJ-3255.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include <functional>
  2. #include <iostream>
  3. #include <limits>
  4. #include <queue>
  5. #include <utility>
  6. #include <vector>
  7. using namespace std;
  8. struct Edge { int to; long long weight; };
  9. int main() {
  10. ios::sync_with_stdio(false);
  11. cin.tie(nullptr);
  12. int n, m; cin >> n >> m;
  13. vector<vector<Edge>> g(n);
  14. while (m--) {
  15. int u, v; long long w; cin >> u >> v >> w; --u; --v;
  16. g[u].push_back({v, w}); g[v].push_back({u, w});
  17. }
  18. const long long inf = numeric_limits<long long>::max() / 4;
  19. vector<long long> first(n, inf), second(n, inf);
  20. priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;
  21. first[0] = 0; pq.push({0, 0});
  22. while (!pq.empty()) {
  23. auto [d, u] = pq.top(); pq.pop();
  24. if (d > second[u]) continue;
  25. for (Edge e : g[u]) {
  26. long long candidate = d + e.weight;
  27. if (candidate < first[e.to]) {
  28. swap(candidate, first[e.to]);
  29. pq.push({first[e.to], e.to});
  30. }
  31. if (first[e.to] < candidate && candidate < second[e.to]) {
  32. second[e.to] = candidate;
  33. pq.push({second[e.to], e.to});
  34. }
  35. }
  36. }
  37. cout << second[n - 1] << '\n';
  38. }