具体学习参考https://blog.csdn.net/qq_35644234/article/details/60870719#commentBox
模板题HDU2544。
O(n^2)
//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;
}
}
Dijkstra+堆优化(O(nlogn))
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll INF=0x3f3f3f3f;
const int maxn=2000005;
using namespace std;
#define pa pair<int,int>
struct node
{
int to,next,v;
};
node edge[maxn];
int cnt=1,head[maxn];
ll dist1[maxn];
void init()
{
memset(head,-1,sizeof(head));
cnt=0;
}
void addedge(int u,int v,int w)
{
cnt++;
edge[cnt].to=v;
edge[cnt].next=head[u];
head[u]=cnt;
edge[cnt].v=w;
}
void Dijkstra(int n,int now,ll dis[])
{
priority_queue<pa,vector<pa>,greater<pa> >q;
int i;
for (i=1;i<=n;i++)
dis[i]=INF;
dis[now]=0;
q.push(make_pair(0,now));
while (!q.empty())
{
now=q.top().second;
q.pop();
for (i=head[now];i;i=edge[i].next)
if (dis[now]+edge[i].v<dis[edge[i].to])
{
dis[edge[i].to]=dis[now]+edge[i].v;
q.push(make_pair(dis[edge[i].to],edge[i].to));
}
}
}
int main()
{
return 0;
}