spfa [template]

Compared with dij, the advantage of spfa is that it can handle the shortest path problem with negative edges and no negative loops, but the disadvantage is that the algorithm complexity is not very good.

 1 void add(int x,int y,int t)
 2 {
 3     edge[tot].to=y;
 4     edge[tot].len=t;
 5     edge[tot].next=next[x];
 6     next[x]=tot++;
 7 }
 8 bool spfa()
 9 {
10     d[1]=0;
11     vis[1]=true;
12     que[front++]=1;
13     cnt[1]++;
14     while(front!=back)
15     {
16         back++;
17         if(back>=1005)back=0;
18         vis[que[back]]=false;
19         for(int i = next[que[back]];i!=-1;i=edge[i].next)
20         {
21             if(d[edge[i].to]>d[que[back]]+edge[i].len)
22             {
23                 d[edge[i].to]=d[que[back]]+edge[i].len;
24                 if(!vis[edge[i].to])
25                 {
26                     que[front++]=edge[i].to;
27                     if(front>=1005)front=0;
28                     vis[edge[i].to]=true;
29                     cnt[edge[i].to]++;
30                     if(cnt[edge[i].to]>n)return false;
31                 }
32             }
33         }
34     }
35     return true;
36 }
View Code

 

Guess you like

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