SPFA is very similar in form and BFS, except that one point in BFS is impossible to re-enter the queue, but SPFA
One point may be placed in the queue again after the queue, that is, after a point has improved the other points, after a period of time may be the
The body is improved, and then used again to refine the other points so that they are repeated iteratively.
Determine if there is a negative loop: If a point enters the queue more than V, there is a negative loop (SPFA cannot process the graph with negative loops).
The need to remember is that it is a different topic, perhaps with SPFA (more than a vis[u]=0) will time out, may also use SPFA more worry, so be flexible.
int BFS (int s)
{
memset (vist,0,sizeof (vist));
memset (dist,0x3f,sizeof (Dist));
int u,v;
queue<int>q;
Vist[s]=1;
dist[s]=0;
Q.push (s);
while (!q.empty ())
{
u=q.front ();
Q.pop ();
for (int i =head[u]; I!=-1 i=edge[i].next)
{
v=edge[i].v;
if (Dist[v] > Dist[u]+edge[i].c)
{
dist[v] = dist[u]+edge[i].c;
if (!vist[v])
{
vist[v]=1;
Q.push (v);
}}} return 0;
}
int SPFA (int s)
{
memset (vist,0,sizeof (vist));
memset (dist,0x3f,sizeof (Dist));
int u,v;
queue<int>q;
Vist[s]=1;
dist[s]=0;
Q.push (s);
while (!q.empty ())
{
u=q.front ();
Q.pop ();
vist[u]=0;//difference in this for
(int i =head[u]; I!=-1 i=edge[i].next)
{
v=edge[i].v;
if (Dist[v] > Dist[u]+edge[i].c)
{
dist[v] = dist[u]+edge[i].c;
if (!vist[v])
{
vist[v]=1;
Q.push (v);
}}} return 0;
}