优化迪杰斯特拉
1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 #define Heap pair<int, int> 5 //第一个int存的是到起点的距离,第二个int存的是点的编号 6 7 using namespace std; 8 9 const int INF = 2147483647; 10 int n, m, t, cnt; 11 int next[1000001], to[1000001], val[1000001], head[10001], dis[10001]; 12 bool vis[1000001]; 13 priority_queue <Heap, vector <Heap>, greater <Heap> > q; 14 //按照第一个int从小到大排序 15 16 inline void add(int a, int b, int c){ 17 to[cnt] = b; 18 val[cnt] = c; 19 next[cnt] = head[a]; 20 head[a] = cnt++; 21 } 22 23 inline void Dijkstra(int s){//以s为起点 24 int i, u, v; 25 Heap x; 26 for(i = 1; i <= n; i++) dis[i] = INF; 27 dis[s] = 0; 28 q.push(make_pair(0, s));//入队 29 while(!q.empty()){ 30 x = q.top(); 31 q.pop(); 32 u = x.second; 33 if(vis[u]) continue;//判断是否已经是最短路径上的点 34 vis[u] = 1; 35 for(i = head[u]; i != -1; i = next[i]){//更新距离 36 v = to[i]; 37 if(dis[v] > dis[u] + val[i]){ 38 dis[v] = dis[u] + val[i]; 39 q.push(make_pair(dis[v], v)); 40 } 41 } 42 } 43 } 44 45 int main(){ 46 int i, j, a, b, c, s; 47 scanf("%d %d %d", &n, &m, &s); 48 memset(head, -1, sizeof(head)); 49 for(i = 1; i <= m; i++){ 50 scanf("%d %d %d", &a, &b, &c); 51 add(a, b, c); 52 } 53 Dijkstra(s); 54 for(i = 1; i <= n; i++) printf("%d ", dis[i]); 55 return 0; 56 }
优化的迪杰斯特拉
但在某些情况下慢
所以写个普通的迪杰斯特拉也是不错的选择
1 const int MAXINT = 32767; 2 const int MAXNUM = 10; 3 int dist[MAXNUM]; 4 int prev[MAXNUM]; 5 int A[MAXUNM][MAXNUM]; 6 void Dijkstra(int v0){ 7 bool S[MAXNUM]; // 判断是否已存入该点到S集合中 8 int n=MAXNUM; 9 for(int i=1; i<=n; ++i){ 10 dist[i] = A[v0][i]; 11 S[i] = false; // 初始都未用过该点 12 if(dist[i] == MAXINT) 13 prev[i] = -1; 14 else 15 prev[i] = v0; 16 } 17 dist[v0] = 0; 18 S[v0] = true; 19 for(int i=2; i<=n; i++){ 20 int mindist = MAXINT; 21 int u = v0; // 找出当前未使用的点j的dist[j]最小值 22 for(int j=1; j<=n; ++j){ 23 if((!S[j]) && dist[j]<mindist){ 24 u = j; // u保存当前邻接点中距离最小的点的号码 25 mindist = dist[j]; 26 } 27 S[u] = true; 28 for(int j=1; j<=n; j++){ 29 if((!S[j]) && A[u][j]<MAXINT){ 30 if(dist[u] + A[u][j] < dist[j]) { //在通过新加入的u点路径找到离v0点更短的路径 31 dist[j] = dist[u] + A[u][j]; //更新dist 32 prev[j] = u; //记录前驱顶点 33 } 34 } 35 } 36 } 37 } 38 }