【模板】最短路之Dijkstra算法

具體學習參考https://blog.csdn.net/qq_35644234/article/details/60870719#commentBox

模板題HDU2544。

//Dijkstra 單源最短路
//權值必須是非負
/*
* 單源最短路徑,Dijkstra 算法,鄰接矩陣形式,複雜度爲O(n^2)
* 求出源 beg 到所有點的最短路徑,傳入圖的頂點數,和鄰接矩陣 cost[][]
* 返回各點的最短路徑 lowcost[], 路徑 pre[].pre[i] 記錄 beg 到 i 路徑上的
父結點,pre[beg]=-1
* 可更改路徑權類型,但是權值必須爲非負
*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
const int MAXN=105;
const int INF=0x3f3f3f3f;//防止後面溢出,這個不能太大
bool vis[MAXN];
int pre[MAXN];
void Dijkstra(int cost[][MAXN],int lowcost[],int n,int beg)
{
    for(int i=1; i<=n; i++)
    {
        lowcost[i]=INF;
        vis[i]=false;
        pre[i]= - 1;
    }
    lowcost[beg]=0;
    for(int j=1; j<n; j++)
    {
        int k= - 1;
        int Min=INF;
        for(int i=1; i<=n; i++)
            if(!vis[i]&&lowcost[i]<Min)
            {
                Min=lowcost[i];
                k=i;
            }
        if(k== - 1)break;
        vis[k]=true;
        for(int i=1; i<=n; i++)
            if(!vis[i]&&lowcost[k]+cost[k][i]<lowcost[i])
            {
                lowcost[i]=lowcost[k]+cost[k][i];
                pre[i]=k;
            }
    }
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m))
    {
        if(!n&&!m)
            break;
        int g[105][105],low[105];
        memset(g,INF,sizeof(g));
        for(int i=0;i<m;i++)
        {
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            g[a][b]=c;
            g[b][a]=c;
        }
        Dijkstra(g,low,n,1);
        cout<<low[n]<<endl;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章