[Remarks] SPFA Classic Optimization

SPFA is very useful for sparse graphs, but it is spicy chicken for dense graphs. . (still great).
Dense graphs can use dij, but does SPFA really lose to dense graphs?
The answer is no, the optimization is strong, let's do it~

Optimization 1: How does SLF
do it?
Suppose we are currently running SPFA's shortest path (both below).
Let our queue head be i, and the number to be added to the queue is j, then we can add the following optimization according to the shortest path.
If dis[j] is less than dis[i], then j is added to the head of the queue, otherwise, Join the tail.
why? Since j is more likely to be the shortest point than i, how about we go first?
How to do it?
Because head=1 must not be possible for the above situation.
Only head>1 has the above situation.
We put head-2 first, because the current head of the team is head, the next +1 will go to head-1,
and then j is placed on head-1:
optimization is about 20%

begin
    if dis[b[x,i]]<dis[d[head]] then  
    begin
        dec(head,2); 
        d[head+1]:=b[x,i];  
    end  
    else  
    begin
        inc(tail);  
        d[tail]:=b[x,i];  
    end;
end;

Optimization 2: LLL,
we can calculate the sum of the dis values ​​of the elements of all queues (head~tail)), and then find the average.
If current head i is greater than this average, that is to say, there is a later It is more likely to be the shortest value than this point.
Then put the number at the head of the queue to the tail of the queue
. Every time you do this, you know that there is one less than or equal to the average.

inc(head);  
ans:=0;  
for i:=head to tail do  
    ans:=ans+dis[d[i]];  
ans:=ans/(tail-head+1);  
while dis[d[head]]>ans do  
begin  
    inc(tail);  
    d[tail]:=d[head]; 
    inc(head);  
end;  
x:=d[head];//后面继续进行SPFA

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326047503&siteId=291194637