Dijkstra
1 #include <iostream>
2 #include <cstring>
3 using namespace std;
4
5 const int INF=0x3fffffff;
6
7 //最短路径
8 struct closedge{
9 int adjvex;
10 int lowcost;
11 bool visited;
12 }closedge[105];
13 int am[105][105];
14 int n,m;
15 int start,end;//started ended
16
17 void printAm();
18 void printLowCost();
19
20 void init(){
21 memset(am,127/3,sizeof(am));
22 cin>>n>>m;
23 int a,b,val;
24 for(int i=1;i<=m;i++){
25 cin>>a>>b>>val;
26 am[a][b]=val;
27 }
28 cin>>start>>end;
29
30 for(int i=1;i<=n;i++){
31 closedge[i].adjvex=start;
32 closedge[i].lowcost=am[start][i];
33 closedge[i].visited=false;
34 }
35 }
36
37 void dijkstra(){
38 int k=n-1;
39 while(k--){
40 //找到最小
41 printLowCost();
42 int min=0x3fffffff,min_i=0;
43 for(int i=1;i<=n;i++){
44 if(!closedge[i].visited&&closedge[i].lowcost<min){
45 min=closedge[i].lowcost;
46 min_i=i;
47 }
48 }
49 closedge[min_i].visited=true;
50 //用这个最小的点去更新closedge
51 for(int i=1;i<=n;i++){
52 if(!closedge[i].visited){
53 if(closedge[i].lowcost>am[min_i][i]+min){
54 closedge[i].lowcost=am[min_i][i]+min;
55 closedge[i].adjvex=min_i;
56 }
57 }
58 }
59 }
60 cout<<closedge[end].lowcost<<endl;
61 }
62
63 void findWay(int end){
64 if(end==start){
65 cout<<start<<" ";
66 }
67 else{
68 findWay(closedge[end].adjvex);
69 cout<<end<<" ";
70 }
71
72
73 }
74
75 int main() {
76 freopen("src/in.txt","r",stdin);
77 init();
78 dijkstra();
79 printAm();
80 findWay(end);
81
82 return 0;
83 }
84
85 void printLowCost(){
86 for(int i=1;i<=n;i++){
87 printf("%10d ",closedge[i].lowcost);
88 }
89 cout<<endl;
90 }
91
92 void printAm(){
93 cout<<start<<" "<<end<<endl;
94 for(int i=1;i<=n;i++){
95 for(int j=1;j<=n;j++){
96 printf("%10d ",am[i][j]);
97 }
98 cout<<endl;
99 }
100 }