acwing 1129

题意:无向边的最短距离

考虑边数小于点数,用SPFA算法,算法复杂度O(me)​

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
#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;
}