Dijkstra算法

Dijkstra算法主要是用来查找单源最短路。

 

Dijkstra算法主要过程:

  用一个dis数组装源点距离其他点的距离。然后每次找到距离最短且未被标记的点,以该点为中转点对其他点进行松弛并标记该点。最终的dis数组就是源点到其他点的最短路径长度。

代码:

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<iostream>
 6 #include<algorithm>
 7 #include<string>
 8 #include<vector>
 9 #include<queue>
10 #include<stack>
11 using namespace std;
12 const int MaxN = 1000;
13 const int Inf = 1 << 30;
14 
15 int pot, eg;//点和边的数量
16 int d[MaxN+5][MaxN+5];//两点距离
17 int s[MaxN+5];//标记点
18 int dis[MaxN+5];//源点到其他点的距离
19 
20 void Dijkstra(int x)
21 {
22     s[x] = 1;
23     int mini, u;
24     for(int no = 1;no < pot;no++)//一共要进行pot-1次
25     {
26         mini = Inf;
27         for(int i = 1;i <= pot;i++)//寻找当前距离源点最近的点
28         {
29             if(s[i]) continue;
30             if(mini > dis[i])
31             { 
32                 mini = dis[i];
33                 u = i;
34             }
35         }
36         s[u] = 1;
37         for(int i = 1;i <= pot;i++)//以该点为中转点对其他点进行松弛
38         {
39             if(d[u][i] < Inf)//防止溢出
40             {
41                 if(dis[i] > dis[u]+d[u][i]) dis[i] = dis[u]+d[u][i];
42             }
43         }
44     }
45 }
46 
47 int main()
48 {
49     cin >> pot >> eg;
50     int a, b, c;
51     for(int i = 1;i <= pot;i++)
52     {
53         for(int j = 1;j <=pot;j++)
54         {
55             if(i == j) d[i][j] = 0;
56             else d[i][j] = Inf;
57         }
58     }
59     for(int i = 1;i <= eg;i++)
60     {
61         cin >> a >> b >> c;
62         d[a][b] = c;
63     }
64     for(int i = 1;i <= pot;i++) dis[i] = d[1][i];
65     Dijkstra(1);
66     for(int i = 1;i <= pot;i++)
67         cout << dis[i] << ' ';
68     cout << endl;
69     return 0;
70 }
posted @ 2018-07-18 11:16  Lightfall  阅读(168)  评论(0编辑  收藏  举报