The two algorithms are essentially the same.
is to extend from one point to the next, constantly updating a dis value until all points are traversed to find the smallest sum of the shortest or the Benquan of a tree.
The naïve algorithm is n^2, can use the heap optimization processing, reduces the complexity to the MLOGN.
But running on a complete picture, at this time m=n^2, the naïve algorithm is rather faster. And the constant is small.
Compared to the SPFA,DIJ can be stable mlogn or n^2.
SPFA theory is ke, but the full picture on the e=n^2, directly multiply a k, and the legend card SPFA is a better card. So when the figure is relatively dense, dij can use, use DIJ.
The biggest advantage of SPFA is the ability to handle negative edge rights.
Dij Code Core: (Heap optimization)
In plain time, simply throw away the priority queue and cycle through the minimum dis value. (also n^2 location)
structpoint{intHao; ll Dis; BOOLFriendoperator<(Point A,point b) {returnA.dis>B.dis; }};p Riority_queue<point>Q;voidDij () {Point St; St.hao=s; St.dis=0; Q.push (ST); inthas=0; while((has!=n) && (!Q.empty ())) { point now=Q.top (); Q.pop (); if(Vis[now.hao])Continue; has++; Vis[now.hao]=1; Dis[now.hao]=Now.dis; for(intI=head[now.hao];i;i=bian[i].nxt) { inty=bian[i].to; if(!Vis[y]) {Point last; Last.hao=y; Last.dis=now.dis+Bian[i].val; Q.push (last); } } }}
Compared with Kruskal, Prim has the advantages of stable complexity n^2 in complete graphs.
Prim can also be optimized with heaps, but it is also simpler and faster on a full map.
The complexity of Kruskal is limited by the sort. The MLOGM is delivered directly. M=n^2 slow fry.
Code Core: (Heap optimization)
In plain time, simply throw away the priority queue and cycle through the minimum dis value. (also n^2 location)
structpoint{intDis,hao; BOOLFriendoperator<(Point A,point b) {returnA.dis>B.dis; }};p Riority_queue<point>Q;intn,m;intsum;BOOLVis[n];BOOLWork () {point now; Now.hao=1; Now.dis=0; inthas=0; Q.push (now); while(has!=n&& (!Q.empty ())) { point now=q.top (); Q.pop (); if(Vis[now.hao])Continue; Vis[now.hao]=1; has++; Sum+=Now.dis; for(intI=head[now.hao];i;i=bian[i].nxt) { inty=bian[i].to; if(!Vis[y]) {Point KK; Kk.hao=y; Kk.dis=Bian[i].val; Q.push (KK); } } } if(has==n)return true; return false;}
Summarize:
1.spfa,kruskal has advantages over sparse graphs.
2.dij,prim on a dense map.
3.dij can not handle negative edge right, SPFA.
Dij and Prim algorithm