-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path多段图的最短路径问题.cpp
More file actions
65 lines (64 loc) · 1.31 KB
/
多段图的最短路径问题.cpp
File metadata and controls
65 lines (64 loc) · 1.31 KB
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
#include<bits/stdc++.h>
using namespace std;
const int N = 20;
const int MAX = 1000;
int arc[N][N]; //存储弧上的权值
int Backpath(int n);
int creatGraph();
int main()
{
int n = creatGraph( );
int pathLen = Backpath(n);
cout<<"最短路径的长度是:"<<pathLen<<endl;
return 0;
}
int creatGraph()
{
int i, j, k;
int weight;
int vnum, arcnum;
cout<<"请输入顶点的个数和边的个数:";
cin>>vnum>>arcnum;
for (i = 0; i < vnum; i++)
for (j = 0; j < vnum; j++)
arc[i][j] = MAX;
for (k = 0; k < arcnum; k++)
{
cout<<"请输入边的两个顶点和权值:";
cin>>i>>j>>weight;
arc[i][j] = weight;
}
return vnum;
}
int Backpath(int n)
{
int i, j, temp;
int cost[N];
int path[N];
for(i = 0; i < n; i++)
{
cost[i] = MAX;
path[i] = -1;
}
cost[0] = 0;
for(j = 1; j < n; j++)
{
for(i = j - 1; i >= 0; i--)
{
if (arc[i][j] + cost[i] < cost[j])
{
cost[j] = arc[i][j] + cost[i];
path[j] = i;
}
}
}
cout<<n-1;
i = n-1;
while (path[i] >= 0)
{
cout<<"<-"<<path[i];
i = path[i];
}
cout<<endl;
return cost[n-1];
}