1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <string> #include <vector> #include <queue>
#define DEBUG(x) std::cerr << #x << " = " << x << std::endl;
using std::cin; using std::cout; using std::endl;
inline int read() { int s = 0, x = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') x = -x; ch = getchar(); } while (isdigit(ch)) { s = s * 10 + ch - '0'; ch = getchar(); } return s * x; }
const int MAXN = 5000 + 10;
struct Edge { int v, w; Edge(int _v = 0, int _w = 0) : v(_v), w(_w) {} };
std::vector<Edge> G[MAXN];
int n, m;
int dist[MAXN][2];
void spfa(int s) { static bool inq[MAXN], vis[MAXN]; memset(dist, 0x3f, sizeof dist); memset(inq, 0, sizeof inq); dist[s][0] = 0; std::queue<int> q; q.push(s); inq[s] = true; while (!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; for (auto e : G[u]) { int v = e.v, w = e.w; if (dist[v][0] > dist[u][0] + w) { dist[v][1] = dist[v][0]; dist[v][0] = dist[u][0] + w; if (!inq[v]) inq[v] = true, q.push(v); } if (dist[v][0] < dist[u][0] + w && dist[v][1] > dist[u][0] + w) { dist[v][1] = dist[u][0] + w; if (!inq[v]) inq[v] = true, q.push(v); } if (dist[v][1] > dist[u][1] + w) { dist[v][1] = dist[u][1] + w; if (!inq[v]) inq[v] = true, q.push(v); } } } }
int main() { n = read(); m = read(); for (int i = 1; i <= m; ++i) { int u = read(); int v = read(); int w = read(); G[u].push_back(Edge(v, w)); G[v].push_back(Edge(u, w)); } spfa(n); printf("%d\n", dist[1][1]); return 0; }
|