以hdu1874畅通工程续为例
1 #include<iostream>
2 #include<cstring>
3 #include<cstdio>
4 #include<queue>
5 using namespace std;
6 const int maxn = 1005;
7 vector<pair<int, int> > E[maxn];
8 int d[maxn], inq[maxn];
9 int n, m,s,t;
10
11 void SPFA(int s)
12 {
13 queue<int> Q;
14 Q.push(s); d[s] = 0, inq[s] = 1;
15 while (!Q.empty())
16 {
17 int now = Q.front(); Q.pop();
18 inq[now] = 0;
19 for (int i = 0; i < E[now].size(); i++) {
20 int v = E[now][i].first;
21 if (d[v] > d[now] + E[now][i].second)
22 {
23 d[v] = d[now] + E[now][i].second;
24 if (inq[v] == 1) continue;
25 inq[v] = 1;
26 Q.push(v);
27 }
28 }
29 }
30 }
31
32 int main()
33 {
34 while (scanf("%d%d",&n,&m)==2)
35 {
36 for (int i = 0; i < maxn; i++) {
37 E[i].clear(); inq[i] = 0, d[i] = 1e9;
38 }
39 for (int i = 0; i < m; i++) {
40 int x, y, z;
41 scanf("%d%d%d", &x, &y, &z);
42 E[x].push_back(make_pair(y, z));
43 E[y].push_back(make_pair(x, z));
44 }
45 scanf("%d%d", &s, &t);
46 SPFA(s);
47 if (d[t] == 1e9)
48 printf("-1
");
49 else
50 printf("%d
", d[t]);
51 }
52 return 0;
53 }