最小堆优化的迪杰斯特拉算法


转自:https://www.cnblogs.com/dustbin/p/6444883.html

文中有一处bug   get()函数中if(heap[now]<=heap[next]) 应改为if(dis[heap[now]]<=dis[heap[next]])

 

算法原理

每次扩展一个距离最小的点,再更新与其相邻的点的距离。

如何寻找距离最小的点

普通的Dijkstra算法的思路是直接For i: 1 to n

优化方案是建一个小根堆,小根堆里存储由当前结点更新距离的所有点,那么堆顶就是距离最小的点

如何寻找与源点相邻的点

当然是邻接表

具体实现

建一个小根堆heap[] ,用来存储结点的序号,用一个数组pos[i] 来存储第i个结点在堆中的位置,用一个标记数组in_heap[] 来记录结点是否在堆中,dis[i] 表示到第i个结点的最短距离

对于小根堆的操作还是基本的put() 和get() ,但由于有的结点已经在堆中了,所以可以把put() 拆为插入堆和调整位置两个部分

完整操作如下:

1.将与源点相邻的点进行松弛操作后加入堆

2.取出位于堆顶的结点

3.若取出的点为终点,则结束算法

4.将与当前结点相邻的点进行松弛操作

​ (1)如果该点已经在堆中,就调整在堆中的位置

​ (2)如果该点不在堆中,就加入堆

5.继续第二步

例题

最短路径问题

时间限制:1秒 内存限制:256兆

题目描述

平面上有n个点(n<=100),每个点的坐标均在-10000~10000之间,其中的一些点之间有连线。若有连线,则表示可从一个点到达另一个点,即两点间有通路,通路的距离为两点间的之间距离。现在的任务是找出一点到另一点之间的最短路径、

输入

输入共有n+m+3行,其中:
第一行为整数n
第2行到第n+1行(共n行),每行两个整数x和y,描述了一个点的坐标(以一个空格分隔)
第n+2行为一个整数m,表示图中连线的个数
此后的m行,每行描述一条连线,由两个整数i和j组成,表示第i个点和第j个点之间有连线
最后一行:两个整数s和t,分别表示源点和目标点

输出

输出仅一行,一个实数(保留两位小数),表示从s到t的最短路径长度

样例输入

5
0 0
2 0
2 2
0 2
3 1
5
1 2
1 3
1 4
2 5
3 5
1 5

样例输出

3.41

代码

#include<cstdio> #include<cstring> #include<cmath> #define MAXN 100+5 struct Edge//邻接表 { int to; double v; Edge *next; }; struct Node { int x,y; }node[MAXN]; int n,m,pos[MAXN],heap_size,s,t,heap[MAXN]; double dis[MAXN]; Edge *first[MAXN]; bool in_heap[MAXN]; void add_edge(int u,int v,double len) { Edge *temp=new Edge; temp->to=v; temp->v=len; temp->next=first[u]; first[u]=temp; } void calc(int i,int j) { double len=sqrt(pow((double)(node[i].x-node[j].x),2)+pow((double)(node[i].y-node[j].y),2)); add_edge(i,j,len); add_edge(j,i,len); } void swapp(int i,int j) { int temp=heap[i]; heap[i]=heap[j]; heap[j]=temp; pos[heap[j]]=j;//调整指针 pos[heap[i]]=i; } void shift_up(int now)//调整位置 { int next=0; while(now>1) { next=now>>1; if(dis[heap[next]]>dis[heap[now]]) swapp(next,now); now=next; } } void put(int x)//插入堆 { in_heap[x]=true; heap[++heap_size]=x; pos[x]=heap_size; shift_up(heap_size); } int get()//取堆顶元素 { int now=1,next,res=heap[1]; in_heap[heap[1]]=false; heap[1]=heap[heap_size--]; pos[heap[1]]=1; while(now*2<=heap_size) { next=now<<1; if(next<heap_size&&dis[heap[next+1]]<dis[heap[next]]) ++next; if(dis[heap[now]]<=dis[heap[next]]) return res; swapp(now,next); now=next; } return res; } void dijkstra() { put(s); dis[s]=0; while(heap_size>0) { int top=get(); if(top==t) break; Edge *temp=first[top]; while(temp!=NULL) { if(dis[temp->to]>dis[top]+temp->v) { dis[temp->to]=dis[top]+temp->v; //结点在堆中就只调整位置,否则插入堆并调整位置 if(in_heap[temp->to]) shift_up(pos[temp->to]); else put(temp->to); } temp=temp->next; } } } int main() { int i,x,y; scanf("%d",&n); for(i=1;i<=n;++i) scanf("%d%d",&node[i].x,&node[i].y); scanf("%d",&m); for(i=1;i<=m;++i) { scanf("%d%d",&x,&y); calc(x,y); } scanf("%d%d",&s,&t); memset(dis,127,sizeof(dis)); dijkstra(); printf("%.2lf\n",dis[t]); return 0; }
dis[


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM