acwing 1129 发表于 2020-04-19 | 分类于 algorithm 题意:无向边的最短距离 考虑边数小于点数,用SPFA算法,算法复杂度O(me) 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162#include <iostream>#include <queue>#include <algorithm>#include <cstring>using namespace std;const int N = 2600, M = 6300 * 2;typedef pair<int, int> PII;int T;int e[M], w[M], ne[M], h[N], idx;int dist[N];int q[N];bool st[N];void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;}int spfa(int s, int ed) { memset(dist, 0x3f, sizeof dist); dist[s] = 0; st[s] = true; int hh = 0, tt = 1; q[0] = s; while(hh != tt) { int t = q[hh ++]; if (hh == N) hh = 0; st[t] = false; for (int i = h[t]; i != -1; i = ne[i]) { int j = e[i]; if (dist[j] > dist[t] + w[i]) { dist[j] = dist[t] + w[i]; if (!st[j]) { st[j] = true; q[++ tt] = j; if (tt == N) tt = 0; } } } } return dist[ed];}int main() { memset(h, -1, sizeof h); int c, s, e; cin >> T >> c >> s >> e; for (int i = 0; i < c; i ++) { int a, b, c; cin >> a >> b >> c; add(a, b, c); add(b, a, c); } cout << spfa(s, e) << endl; return 0;}