最短路径(Dijkstra)-HDU 2544-最短路

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SZU_Crayon/article/details/82290831
  • 最短路径(Dijkstra)-HDU 2544-最短路


  • 题目链接:

最短路

  • 题目基础:

最短路径-Dijkstra(迪杰斯特拉)算法

  • 思路:

题目大意:

略略略~~

题解:

套模板,传送门有详解

  • 代码:

#include <iostream>
#include<memory.h>
using namespace std;
#define MAX_SIZE 1024
#define INF 65535

//邻接图
struct MGrapth
{
    int Vexs[MAX_SIZE];  //顶点表
    int Arc[MAX_SIZE][MAX_SIZE];  //邻接矩阵
    int Num_Vertext,Num_Edges;  //顶点数,边数
};
MGrapth Map;

int Path[MAX_SIZE];   /*表示路径 Path[i]->i*/
int Short_Path[MAX_SIZE]; /*Start->i 的最短路径和*/
bool Vis[MAX_SIZE];   /*当前最短路径结点true*/

void Init(int n,int m)
{
    Res=0;
    memset(Vis,0,sizeof(Vis));
    memset(Path,0,sizeof(Path));
    for(int i=0;i<=n;i++)
        for(int j=0;j<=m;j++)
            Map.Arc[i][j]=INF;
    Map.Num_Vertext=n;
    Map.Num_Edges=m;
}

void Dijkstra(int Start)
{
    int v,w,k,Min;
    for(v=0;v<Map.Num_Vertext;v++)
        Short_Path[v]=Map.Arc[Start][v];  /*Start到相连结点的距离*/

    Short_Path[Start]=0;   /*Start->Start 的距离为0*/
    Vis[Start]=1;   /*Start为当前最短路径结点*/

    for(v=1;v<Map.Num_Vertext;v++)
    {
        Min=INF;
        for(w=0;w<Map.Num_Vertext;w++)
        {
            if(!Vis[w]&&Short_Path[w]<Min)
            {
                k=w;
                Min=Short_Path[w];
            }
        }
        Vis[k]=true; /*找出最短路到散点的最小值,将该散点连入最短路*/

        for(w=0;w<Map.Num_Vertext;w++)  /*更新最短路*/
        {
            if(!Vis[w]&&Min+Map.Arc[k][w]<Short_Path[w])  /*图中某点到v0的距离比当前路短,更新*/
            {
                Short_Path[w]=Min+Map.Arc[k][w];
                Path[w]=k;
            }
        }
    }
}

int main()
{
    int M,N;
    int A,B,C;
    while(cin>>N>>M)
    {
        if(N==0&&M==0)
            break;
        Init(N,M);
        for(int i=0;i<M;i++)
        {
            cin>>A>>B>>C;
            if(Map.Arc[A-1][B-1]>C)   //最小坐标当成0来写
                Map.Arc[A-1][B-1]=C;
            if(Map.Arc[B-1][A-1]>C)
                Map.Arc[B-1][A-1]=C;
        }
        Dijkstra(0);
        cout<<Short_Path[N-1]<<endl;
   }
   return 0;
}

猜你喜欢

转载自blog.csdn.net/SZU_Crayon/article/details/82290831
今日推荐