1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
Procedure SPFA;
Begin
initialize-single-source(G,s);
initialize-queue(Q);
enqueue(Q,s);
while
not empty(Q)
do
begin
u:=dequeue(Q);
for
each v∈adj[u]
do
begin
tmp:=d[v];
relax(u,v);
if
(tmp<>d[v]) and (not v in Q) then
enqueue(Q,v);
end;
end;
End;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
ProcedureSPFA;
Begin
initialize-
single
-source(G,s);
initialize-queue(Q);
enqueue(Q,s);
while
not
empty(Q)
do
begin
u:=dequeue(Q);
for
each v∈adj[u]
do
begin
tmp:=d[v];
relax(u,v);
if
(tmp<>d[v])
and
(
not
v
in
Q)
then
enqueue(Q,v);
end
;
end
;
End
;
|
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
#include <iostream>
#include <deque>
#include <stack>
#include <vector>
using
namespace
std;
const
int
MAXN=100;
const
int
INF=0x7FFFFFFF;
struct
edge
{
int
to,weight;
};
vector<edge> adjmap[MAXN];
//邻接表
bool
in_queue[MAXN];
//顶点是否在队列中
int
in_sum[MAXN];
//顶点入队次数
int
dist[MAXN];
//源点到各点的最短路径
int
path[MAXN];
//存储到达i的前一个顶点
int
nodesum;
//顶点数
int
edgesum;
//边数
bool
SPFA(
int
source)
{
deque<
int
> dq;
int
i,j,x,to;
for
(i=1;i<=nodesum;i++)
{
in_sum[i]=0;
in_queue[i]=
false
;
dist[i]=INF;
path[i]=-1;
}
dq.push_back(source);
in_sum[source]++;
dist[source]=0;
in_queue[source]=
true
;
//初始化完成
while
(!dq.empty())
{
x=dq.front();
dq.pop_front();
in_queue[x]=
false
;
for
(i=0;i<adjmap[x].size();i++)
{
to=adjmap[x][i].to;
if
((dist[x]<INF)&&(dist[to]>dist[x]+adjmap[x][i].weight))
{
dist[to]=dist[x]+adjmap[x][i].weight;
path[to]=x;
if
(!in_queue[to])
{
in_queue[to]=
true
;
in_sum[to]++;
if
(in_sum[to]==nodesum)
return
false
;
if
(!dq.empty())
{
if
(dist[to]>dist[dq.front()]) dq.push_back(to);
else
dq.push_front(to);
}
else
dq.push_back(to);
}
}
}
}
return
true
;
}
void
Print_Path(
int
x)
{
stack<
int
> s;
int
w=x;
while
(path[w]!=-1)
{
s.push(w);
w=path[w];
}
cout<<
"顶点1到顶点"
<<x<<
"的最短路径长度为:"
<<dist[x]<<endl;
cout<<
"所经过的路径为:1"
;
while
(!s.empty())
{
cout<<s.top()<<
""
;
s.pop();
}
cout<<endl;
}
int
main()
{
int
i,s,e,w;
edge temp;
cout<<
"输入顶点数和边数:"
;
cin>>nodesum>>edgesum;
for
(i=1;i<=nodesum;i++)
adjmap[i].clear();
//清空邻接表
for
(i=1;i<=edgesum;i++)
{
cout<<
"输入第"
<<i<<
"条边的起点、终点还有对应的权值:"
;
cin>>s>>e>>w;
temp.to=e;
temp.weight=w;
adjmap[s].push_back(temp);
}
if
(SPFA(1))
{
for
(i=2;i<=nodesum;i++) Print_Path(i);
}
else
cout<<
"图中存在负权回路"
<<endl;
return
0;
}
|