Skip to content

Bellman Ford's prev doesn't get properly updated #300

Closed

Description

@JJCUBER

I've noticed that it's possible for a spot to have -inf distance but -1 as prev. I believe this is due to how a reduced number of iterations are performed followed by an extra loop at the end to propagate -inf.

I believe making this modification would fix it, but I wanted to get additional feedback on this before proposing it (in case some of the optimizations applied would lead to this not fully resolving the issue):

	rep(i,0,lim) for (Ed e : eds) {
-		if (nodes[e.a].dist == -inf)
+		if (nodes[e.a].dist == -inf) {
+			nodes[e.b].prev = e.a;
			nodes[e.b].dist = -inf;
+		}
	}

For reference: https://github.com/kth-competitive-programming/kactl/blob/eab6492ce9c8549832484f47276739ff120477b3/content/graph/BellmanFord.h#L32C1-L35C3

Activity

  1. ItsDeadlyProgrammer commented on Oct 9, 2026

    @ItsDeadlyProgrammer

    I've opened #325 with this fix (setting prev = e.a in the propagation loop). It also adds a stress test for BellmanFord. On current main it finds -inf nodes with prev = -1 or with a prev whose distance isn't -inf, and with the change all checks pass.

  2. JJCUBER commented on Oct 9, 2026

    @JJCUBER
    ContributorAuthor

    Closing unless/until I recall what the edge case I ran into was since it seems like this doesn't really "fix" anything per se.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions