“堆优化版spfa”顾名思义,我们将spfa中的队列改成二叉堆(优先队列),就可以得到这个版本的spfa。
首先我们先要验证其可行性,spfa的核心松弛逻辑是如果此节点可以松弛一个节点,就加入队列,继续松弛其他节点。从这个角度上来讲,堆优化没问题,只是会痛失spfa的BFS性质。
从(最差)时间复杂度上分析,spfa本来的时间复杂度是o(nm)。这里有一个误区,就是我们会认为“堆优化”不仅不会优化,还会增加一个因子logn。
我们可以从数学上证明,这个算法的主循环最多会循环n+m(如果是无向图m要乘2)次,那这就简单了,设c=n+m,这个算法的最坏时间复杂度就是o(c×logc)。
并且我们还发现,这个算法和无标记数组的堆优化版Dijkstra运算逻辑100%相同。
并且此算法还满足一个性质:
- 如果一个节点重复入堆,那么这个节点的松弛节点必定不会与之前的松弛节点相同。
通过这个性质,我们也可以推导出时间复杂度是o(c×logc)。
于是,我们就得到了这个算法的代码:
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+8,M=2e6+8,C=0x3f3f3f3f;
struct G{int x,u,t;} a[M<<1];
struct spf{
int x,u;
bool operator<(const spf&other)const{return u>other.u;}
};
int n,m,h[N],cnt=0,ans[N];
inline void spfa(int s){
priority_queue<spf>sta;
memset(ans,C,sizeof(ans));
ans[s]=0,sta.push({s,0});
while (!sta.empty()){
int u=sta.top().x;sta.pop();
for (int i=h[u];i;i=a[i].t)
if (ans[a[i].x]>ans[u]+a[i].u)
ans[a[i].x]=ans[u]+a[i].u,sta.push({a[i].x,ans[a[i].x]});
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int s;
cin >>n>>m>>s;
for (int i=1,x,y,z;i<=m;i++){
cin >>x>>y>>z;
cnt++;a[cnt]={y,z,h[x]};h[x]=cnt;
}spfa(s);
for (int i=1;i<=n;i++) cout <<ans[i]<<" ";
return 0;
}