Dijkstra优先队列优化

Dijkstra算法的核心思想就是两步排序,一个是对于一个点而言,他的最小边要经过所有其他点最小边的测试才能确认,也就是说要在这其中找一个最大的边出来;第二个是对于每次循环而言的,每次的更新d数组都是为了要选出最短的距离。
对于每次出队列的点,都更新他所有的邻边
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define INF 65535
using namespace std;
 
typedef pair<int,int> Node;
int n,m;
int G[107][107];
 
bool operator < (Node a,Node b)
{
 return a.first > b.first;
}
 
int Dijkstra()
{
 int v,min;
 int d[107];
 int vis[107];
 priority_queue<Node> q;
 memset(vis,0,sizeof(vis));
 for(int i = 1;i <= n;i++)
  d[i] = INF;
 d[1] = 0;
 q.push(make_pair(d[1],1));
 while(!q.empty()) {
  Node t = q.top();
  q.pop();
  if(vis[t.second])
   continue;
  vis[t.second] = 1;
  for(int i = 1;i <= n;i++)
   if(!vis[i] && d[i] > t.first+G[t.second][i]) {
    d[i] = t.first+G[t.second][i];
    q.push(make_pair(d[i],i));
   }
 }
 return d[n];
}
int main()
{
 int x,y,w;
 while(~scanf("%d%d",&n,&m))
 {
  if(!n && !m) break;
  for(int i = 1;i <= n;i++)
   for(int j = 1;j <= n;j++)
    G[i][j] = i==j?0:INF;
  for(int i = 1;i <= m;i++) {
   scanf("%d%d%d",&x,&y,&w);
   if(w < G[x][y])
    G[x][y] = G[y][x] = w;
  }
  printf("%d
",Dijkstra());
 }
 return 0;
}
原文地址:https://www.cnblogs.com/immortal-worm/p/4991247.html