Skip to content

Optimize heap operations in min-cost flow slope calculation - #30

Merged
shakayami merged 1 commit into
masterfrom
claude/mincostflow-heapq-optimize-8gnbrb
Jul 11, 2026
Merged

Optimize heap operations in min-cost flow slope calculation#30
shakayami merged 1 commit into
masterfrom
claude/mincostflow-heapq-optimize-8gnbrb

Conversation

@shakayami

Copy link
Copy Markdown
Owner

Summary

This PR optimizes the heap operations in the slope() method of the min-cost flow algorithm by encoding node information directly into heap values instead of using tuples.

Key Changes

  • Cache self.n: Store self.n in a local variable n to reduce repeated attribute lookups
  • Simplify heap pushes: Replace tuple-based heap entries (distance, node) with encoded integer values:
    • Initial push: s instead of (0, s)
    • Subsequent pushes: dist[e["to"]] * n + e["to"] instead of (dist[e["to"]], e["to"])
  • Update heap pops: Decode the integer values back to node indices:
    • heapq.heappop(que) % n instead of heapq.heappop(que)[1]

Implementation Details

The optimization encodes both distance and node information into a single integer by using the formula distance * n + node_id. This allows the heap to naturally sort by distance (primary) and node ID (secondary) while reducing memory overhead and tuple allocation overhead. The node is recovered using modulo arithmetic during dequeue operations.

https://claude.ai/code/session_011Ns3CZfpPTnJM3tDqCaDVt

…omparison

Encode (dist, vertex) as dist*n+v so heapq operates on plain integers
instead of tuples, eliminating per-push/pop tuple allocation and
element-wise comparison overhead.
@shakayami shakayami linked an issue Jul 11, 2026 that may be closed by this pull request
@shakayami
shakayami merged commit 31168cc into master Jul 11, 2026
19 checks passed
@shakayami
shakayami deleted the claude/mincostflow-heapq-optimize-8gnbrb branch July 11, 2026 07:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mincostflow

2 participants