Skip to content

Commit 851eddf

Browse files
authored
队列优化的Bellman-Ford算法(SPFA算法)
1 parent 08319f0 commit 851eddf

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

Bellman-Ford(Queue-Optimised).cpp

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#include <cstdio>
2+
3+
#define INF 1000000000
4+
5+
using namespace std;
6+
7+
struct vertex
8+
{
9+
int first_edge;
10+
int dis;
11+
}V[100010];
12+
13+
struct edge
14+
{
15+
int endp, next;
16+
int w;
17+
}E[1000010];
18+
19+
int ec = 1;
20+
int ivc, iec;
21+
22+
int Q[200000];
23+
int hp = 0, tp = 0;
24+
25+
void enqueue(int x)
26+
{
27+
Q[tp] = x;
28+
tp++;
29+
tp %= 200000;
30+
}
31+
32+
int dequeue()
33+
{
34+
int ret = Q[hp];
35+
hp++;
36+
hp %= 200000;
37+
return ret;
38+
}
39+
40+
bool empty()
41+
{
42+
return hp == tp;
43+
}
44+
45+
void add_edge(int u, int v, int w)
46+
{
47+
E[ec].next = V[u].first_edge;
48+
V[u].first_edge = ec;
49+
E[ec].endp = v;
50+
E[ec].w = w;
51+
ec++;
52+
}
53+
54+
void initial_single_source(int s)
55+
{
56+
for (int i = 1; i <= ivc; i++)
57+
{
58+
V[i].dis = INF;
59+
}
60+
V[s].dis = 0;
61+
}
62+
63+
void SPFA(int s)
64+
{
65+
initial_single_source(s);
66+
enqueue(s);
67+
while (!empty())
68+
{
69+
int u = dequeue();
70+
for (int cur = V[u].first_edge; cur != 0; cur = E[cur].next)
71+
{
72+
int newdis = V[u].dis + E[cur].w;
73+
if (newdis < V[E[cur].endp].dis)
74+
{
75+
V[E[cur].endp].dis = newdis;
76+
enqueue(E[cur].endp);
77+
}
78+
}
79+
}
80+
}
81+
82+
int main()
83+
{
84+
scanf("%d%d", &ivc, &iec);
85+
for (int i = 0; i < iec; i++)
86+
{
87+
int u, v, w;
88+
scanf("%d%d%d", &u, &v, &w);
89+
add_edge(u, v, w);
90+
add_edge(v, u, w);
91+
}
92+
SPFA(1);
93+
printf("%d", V[ivc].dis);
94+
return 0;
95+
}

0 commit comments

Comments
 (0)