0%

最短路

最短路

以下为数据结构作业
如有错误,请指出,谢谢!

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
#include<bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f3f;
int N,M,MAP[1020][1020];
bool vis[1020];
int dis[1020],prev[1020];
void Dijkstra(int start,int end)
{
for(int i=1;i<=N;i++)
{
vis[i]=false;
dis[i]=INF;
}
dis[start]=0;
while(true)
{
int v=-1;
for(int u=1;u<=N;u++)
if(!vis[u]&&(v==-1||dis[u]<dis[v]))v=u;
if(v==-1)break;
vis[v]=true;
for(int u=1;u<=N;u++)
{
if(!vis[u])
{
if(dis[u]>dis[v]+MAP[v][u])
{
dis[u]=dis[v]+MAP[v][u];
prev[u]=v;
}
}
}
}
cout<<"The Shortest Path Length is "<<dis[end]<<endl<<endl;
stack<int>S;
while(prev[end])
{
S.push(end);
end=prev[end];
}
cout<<"The Path is ";
cout<<start;
while(!S.empty())
{
cout<<" -> "<<S.top();
S.pop();
}
}
int main()
{
int a,b,c,st,en;
cout<<"Input Sum Of Vertex: ";
cin>>N;
cout<<"Input Sum Of Edges: ";
cin>>M;
memset(MAP,INF,sizeof(MAP));
cout<<"Input Weight Of Vertexs: "<<endl;
while(M--)
{
cin>>a>>b>>c;
MAP[a][b]=c;
MAP[b][a]=c;
}
cout<<endl<<"Adjacency Matrix is:"<<endl;
for(int i=1;i<=N;i++)
{
for(int j=1;j<=N;j++)
{
if(MAP[i][j]==INF)printf("INF ");
else printf("%03d ",MAP[i][j]);
}
cout<<endl;
}
cout<<endl<<"Input Two Vertexs: ";
cin>>st>>en;
cout<<endl;
Dijkstra(st,en);
return 0;
}

赏点呗!