Skip to content

Commit 79da6b7

Browse files
committed
add shortest path faster algorithm
1 parent 6d7cf87 commit 79da6b7

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

template/Graph/SPFA.cpp

+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// Shortest Path Faster Algorithm
2+
#include <iostream>
3+
#include <queue>
4+
using namespace std;
5+
6+
const int maxn = 1005;
7+
const int maxm = 20005;
8+
const int inf = 0x3f3f3f3f;
9+
10+
struct edge{
11+
int v, w;
12+
int next;
13+
};
14+
15+
int total;
16+
int head[maxn];
17+
edge e[maxm];
18+
19+
int dis[maxn];
20+
int inqueue[maxn];
21+
int cnt[maxn];
22+
23+
void init(int n) {
24+
total = 0;
25+
for (int i = 0; i < n; i ++) {
26+
head [i] = -1;
27+
}
28+
}
29+
30+
void addedge(int u, int v, int w) {
31+
e[total].v = v;
32+
e[total].w = w;
33+
e[total].next = head[u];
34+
head[u] = total;
35+
total ++;
36+
}
37+
38+
int spfa (int n, int s, int t = -1) {
39+
for (int i = 0; i < n; i ++) {
40+
dis[i] = inf;
41+
inqueue[i] = 0;
42+
cnt[i] = 0;
43+
}
44+
queue<int> que;
45+
que.push(s);
46+
inqueue[s] = 1;
47+
cnt[s] = 1;
48+
dis[s] = 0;
49+
while (!que.empty()) {
50+
int u = que.front();
51+
que.pop();
52+
inqueue[u] = 0;
53+
for (int i = head[u]; i != -1; i = e[i].next) {
54+
int v = e[i].v;
55+
if (dis[u] + e[i].w < dis[v]) {
56+
dis[v] = dis[u] + e[i].w;
57+
if (!inqueue[v]) {
58+
que.push(v);
59+
inqueue[v] = 1;
60+
cnt[v] ++;
61+
if (cnt[v] > n) {
62+
return -1;
63+
}
64+
}
65+
}
66+
}
67+
}
68+
if (t == -1) {
69+
t = n - 1;
70+
}
71+
return dis[t];
72+
}
73+
74+
int main(int argc, char const *argv[]) {
75+
int n, m, s, t;
76+
int u, v, w;
77+
int des;
78+
while (scanf ("%d%d%d", &n, &m, &s) == 3) {
79+
init(n);
80+
s --;
81+
for (int i = 0; i < m; i ++) {
82+
scanf ("%d%d%d", &u, &v, &w);
83+
u --;
84+
v --;
85+
addedge(v, u, w);
86+
}
87+
spfa(n, s);
88+
scanf ("%d", &t);
89+
int ans = inf;
90+
for (int i = 0; i < t; i ++) {
91+
scanf ("%d", &des);
92+
ans = min(ans, dis[des - 1]);
93+
}
94+
if (ans == inf) {
95+
ans = -1;
96+
}
97+
cout << ans << "\n";
98+
}
99+
return 0;
100+
}

0 commit comments

Comments
 (0)