【数据结构】单源最短路径dijkstra算法描述及模板
目录
1.算法步骤:
2.模板代码
Dijkstra算法用于解决单源最短路径问题,适用于有向或无向图,要求所有边的权重非负。其核心思想是通过贪心策略逐步确定从起点到其他所有节点的最短路径。
1.算法步骤:
-
设置起点到自身的距离为
0
,其他节点为无穷大(INF
)。 -
使用优先队列(最小堆)保存待处理的节点及其当前最短距离。
-
每次从队列中取出距离最小的节点
u
。 -
若
u
的最短距离已更新(队列中的值大于记录值),跳过。 -
否则,遍历
u
的所有邻接节点v
,进行松弛操作。 -
若通过
u
到达v
的路径更短,则更新v
的最短距离,并将v
加入队列。 -
队列为空时,算法结束。此时距离数组保存了起点到所有节点的最短距离。
2.模板代码
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <queue>
using namespace std;
const int maxn=1e3;
const int inf=0x3f3f3f3f;
int n,m,s,dd;
struct edge
{
int to,cost,dist;
edge(int _to,int _dist,int _cost)
{
to=_to;
cost=_cost;
dist=_dist;
}
};
struct node
{
int u;
int di;
int co;
node(int _u,int _di,int _co)
{
u=_u;
di=_di;
co=_co;
}
bool operator <(const node &e)const
{
if(di==e.di)
{
return co>e.co;
}
return di>e.di;
}
};
int d[maxn];
int c[maxn];
bool vis[maxn];
vector<edge> g[maxn];
void dijkstra(int s)
{
priority_queue<node> q;
for(int i=0;i<maxn;i++)
{
d[i]=inf;
}
for(int i=0;i<maxn;i++)
{
c[i]=inf;
}
d[s]=0;
c[s]=0;
memset(vis,0,sizeof(vis));
q.push(node(s,0,0));
while(!q.empty())
{
node x=q.top();
q.pop();
int u=x.u;
if(vis[u])
{
continue;
}
vis[u]=true;
for(int i=0;i<g[u].size();i++)
{
edge e=g[u][i];
//cout<<u<<" "<<e.to<<" "<<d[u]+e.dist<<" "<<d[e.to]<<" "<<c[u]+e.cost<<" "<<c[e.to]<<endl;
if((d[e.to]>d[u]+e.dist)||((d[e.to]==d[u]+e.dist)&&(c[e.to]>c[u]+e.cost)))
{
d[e.to]=d[u]+e.dist;
c[e.to]=c[u]+e.cost;
q.push(node(e.to,d[e.to],c[e.to]));
}
}
}
}
int main()
{
cin>>n>>m>>s>>dd;
for(int i=0;i<maxn;i++)
{
g[i].clear();
}
for(int i=0;i<m;i++)
{
int x,y,co,di;
cin>>x>>y>>di>>co;
g[x].push_back(edge(y,di,co));
g[y].push_back(edge(x,di,co));
}
dijkstra(s);
cout<<d[dd]<<" "<<c[dd]<<endl;
}