最短路之dijkstra 算法

来源:互联网 发布:ubuntu 服务器下载 编辑:程序博客网 时间:2024/05/17 03:21
#include <cstdio>  #include <cstring>  const int N = 110;  const int inf = 99999999;  int cost[N][N];  int d[N];  bool deleted[N];  int n , m;  //假设点从1开始  //初始化矩阵cost,以及距离标号d  void Prepare(int s)   {      for(int i = 1; i <= n; i++)      {          cost[i][i] = 0;          for(int j = i + 1; j <= n; j++)          {              cost[i][j] = cost[j][i] = inf;          }      }      for(int i = 1; i <= n; i++)  d[i] = inf;      d[s] = 0;      for(int i = 1; i <= n; i++) deleted[i] = false;  }  int Shortest_Path()  {      while(true)      {          int decided = -1;          for(int i = 1; i <= n; i++) if(!deleted[i])          {              if(decided == -1 || d[i] < d[decided])  decided = i;          }          if(decided == -1) break;          //可以输出看一下哪些点的最短路依次确定了          //printf("decided=%d\n",decided);          for(int i = 1; i <= n; i++)          {              if(d[decided] + cost[decided][i] < d[i])              {                  d[i] = d[decided] + cost[decided][i];              }          }          deleted[decided] = true;      }      return d[n];  }  int main()  {      int a,b,c;      while(scanf("%d%d",&n,&m),(n||m))      {          Prepare(1);          for(int i = 0; i < m; i++)          {              scanf("%d%d%d",&a,&b,&c);              if(c < cost[a][b])              {                      cost[a][b] = c;                      cost[b][a] = c;              }          }          printf("%d\n",Shortest_Path());      }  }  

原创粉丝点击