{"id":258,"date":"2026-11-13T12:36:08","date_gmt":"2026-11-13T04:36:08","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-spfa-queues-bellman-ford-relaxations\/"},"modified":"2026-11-13T21:53:52","modified_gmt":"2026-11-13T13:53:52","slug":"how-spfa-queues-bellman-ford-relaxations","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-spfa-queues-bellman-ford-relaxations\/","title":{"rendered":"How SPFA queues Bellman-Ford relaxations"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>SPFA<\/strong> is the queue form of <strong>Bellman-Ford<\/strong>. A vertex enters the queue when its distance improves, and it relaxes its outgoing edges when it leaves. A vertex already in the queue is not inserted twice. The worst case is still <strong>\u0398(VE)<\/strong>, and there are families of graphs that force that behavior. A vertex dequeued <strong>|V|<\/strong> times is a reachable <strong>negative cycle<\/strong>. Small-label and large-label heuristics change the order inside the queue and do not change the worst case.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Bellman-Ford relaxes every edge on every round, including edges whose tail did not improve. The queue version relaxes an edge only when its tail has a new distance. On many sparse graphs with short dependency chains the queue stays small and the run looks almost linear. That observation is not a complexity bound.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The danger is publishing the typical speed as if it were Dijkstra&#8217;s guarantee. Nonnegative weights already have Dijkstra. Negative weights have Bellman-Ford&#8217;s worst case, and SPFA inherits it, sometimes with a larger constant on the bad families.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">If no negative cycle is reachable, the queue eventually empties and the distances match Bellman-Ford&#8217;s. Each successful relaxation enqueues a vertex, and a simple implementation that counts dequeues can stop when any vertex has been dequeued |V| times, which is a negative-cycle witness. Time is O(VE) and can be \u0398(VE). Extra memory is the queue and the distance array.<\/p>\n\n\n<p class=\"wp-block-paragraph\">SLF and LLL are queue-ordering heuristics: put a small new distance near the front, or swap when the front is much larger than the average. They often reduce the number of relaxations on random graphs. They are not an asymptotic improvement, and a worst-case family remains worst-case after either tweak. Nonnegative input should call Dijkstra instead. SPFA does not become Dijkstra by using a queue.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Set dist[source] = 0 and enqueue the source. A boolean records whether a vertex is already in the queue.<\/li>\n<li>Dequeue u and clear its in-queue flag. For each edge u\u2192v, if dist[u]+w &lt; dist[v], update dist[v] and parent[v], and enqueue v if it is not already queued.<\/li>\n<li>Count dequeues of each vertex. A count of |V| means a negative cycle is reachable. Stop and report it.<\/li>\n<li>If the queue empties first, the distances are shortest-path distances.<\/li>\n<li>Optional SLF: insert an improved vertex at the front when its distance is smaller than the front&#8217;s, otherwise at the back. Treat this as a heuristic, and keep the dequeue counter.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The algorithm is a scheduling of Bellman-Ford, useful as a practical negative-edge search with an explicit worst case of \u0398(VE). It is the wrong default for nonnegative road networks, contest graphs with a trap family, or any caller who will read a blog&#8217;s &#8220;average linear&#8221; line as a promise. Dijkstra, 0-1 BFS, and Dial already cover the nonnegative special cases in real bounds.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the queue is described as always faster than Bellman-Ford<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Quote average-case linear time as the complexity<\/td>\n<td>The worst case is \u0398(VE). A guarantee that omits it will time out on a known family.<\/td>\n<\/tr>\n<tr>\n<td>Use SPFA because the graph might contain a negative edge, without a cycle check<\/td>\n<td>A reachable negative cycle makes the queue run until the dequeue cap. Without the cap it does not terminate.<\/td>\n<\/tr>\n<tr>\n<td>Prefer it to Dijkstra on nonnegative weights<\/td>\n<td>Dijkstra&#8217;s heap has a proved O((V+E) log V) bound and settles each vertex once. The queue does not use nonnegativity.<\/td>\n<\/tr>\n<tr>\n<td>Drop the in-queue flag and push on every relaxation<\/td>\n<td>A vertex can then sit in the queue many times per improvement wave. The usual linear-size queue argument goes away, and the results need a careful reread.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Nonnegative weights belong to Dijkstra or to a bucket queue when the weights are small integers. A simple worst-case implementation with negative edges belongs to the plain double loop of Bellman-Ford, which has the same bound and no heuristic to misread.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment queues a vertex when an edge relaxes it, which is Bellman\u2013Ford with a queue. Edges 0\u21921 weight 1 and 1\u21922 weight 2 produce distances <code>0 1 3<\/code>. A second graph with a negative cycle is reported as <code>cycle<\/code>.<\/p>\n\n<pre><code class=\"language-python\">from collections import deque\n\ndef spfa(n, edges, src=0):\n    dist = [10**9] * n\n    dist[src] = 0\n    count = [0] * n\n    inq = [False] * n\n    q = deque([src])\n    inq[src] = True\n    while q:\n        u = q.popleft()\n        inq[u] = False\n        for v, w in edges[u]:\n            if dist[u] + w &lt; dist[v]:\n                dist[v] = dist[u] + w\n                count[v] += 1\n                if count[v] &gt;= n:\n                    return None\n                if not inq[v]:\n                    q.append(v)\n                    inq[v] = True\n    return dist\n\nok = spfa(3, [[(1, 1)], [(2, 2)], []])\nbad = spfa(2, [[(1, 1)], [(0, -2)]])\nassert ok == [0, 1, 3] and bad is None\nprint(*ok, &quot;cycle&quot; if bad is None else &quot;no&quot;)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">SPFA, a queue of Bellman-Ford relaxations, is sometimes fast on casual graphs and can be pushed back to the slow bound by a bad one. It is not a safe library default. Dijkstra handles nonnegative weights, and a plain Bellman-Ford has a predictable limit.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop SPFA as a library default. Use Dijkstra when weights are nonnegative and the plain Bellman-Ford loop when they are not and the graph is moderate. Keep the queue version when negative edges are real, the graph is large and sparse, and a dequeue cap of |V| is in the code so a negative cycle cannot spin.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for SPFA returns the queue, the |V| dequeue cap, and the \u0398(VE) worst case that the heuristics do not remove. <strong>SPFA is Bellman-Ford scheduled by a queue, still \u0398(VE) in the worst case, and a vertex dequeued |V| times is a reachable negative cycle.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: SPFA is the queue form of Bellman-Ford. A vertex enters the queue when its distance improves, and it relaxes its outgoing edges when it leaves. A vertex already in the queue is not inserted twice. The worst case is still \u0398(VE), and there are families of graphs&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,32],"tags":[],"class_list":["post-258","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-graphs"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/258","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=258"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/258\/revisions"}],"predecessor-version":[{"id":657,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/258\/revisions\/657"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=258"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=258"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=258"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}