// 点数,边数,源点到各点最短距离,起点,访问标记,链式head
int n,m,dist[maxn],s,vis[maxn],head[maxn];
struct edge{
int to,val,ne;
}edge[maxn];
struct node{
int val,pos;
friend bool operator <(struct node a,struct node b){
return a.val>b.val;
}
};
priority_queue<node> q; // 堆优化
void add_edge(int now,int to,int val,int tot){
edge[tot].ne=head[now];
head[now]=tot;
edge[tot].to=to;
edge[tot].val=val;
}
void dij(){
for(int i=1;i<=n;i++) if(i!=s) dist[i]=inf;
q.push({0,s});
while(!q.empty()){
struct node top=q.top();
q.pop();
if(vis[top.pos]) continue;
vis[top.pos]=1;
for(int i=head[top.pos];i;i=edge[i].ne){
int to_val=top.val+edge[i].val;
int to_pos=edge[i].to;
if(dist[to_pos]>to_val){
dist[to_pos]=to_val;
q.push({to_val,to_pos});
}
}
}
}
最短路dij模板(堆优化)
最新推荐文章于 2024-05-28 16:53:43 发布
这篇博客详细介绍了如何运用优先队列(堆)优化Dijkstra算法,以找到图中从源点到所有其他点的最短路径。代码中定义了边结构、节点结构,并通过add_edge函数添加边,dij函数实现了Dijkstra算法的核心逻辑,不断更新最短路径并维护最小堆。
245

被折叠的 条评论
为什么被折叠?



