Skip to content

Add shorter and faster Hopcroft-Karp implementation#308

Merged
simonlindholm merged 2 commits intokth-competitive-programming:mainfrom
ahsoltan:new-matching
Jan 25, 2026
Merged

Add shorter and faster Hopcroft-Karp implementation#308
simonlindholm merged 2 commits intokth-competitive-programming:mainfrom
ahsoltan:new-matching

Conversation

@ahsoltan
Copy link
Contributor

About 2x faster on library checker tests than the old one:

Also about 2x shorter.

@simonlindholm
Copy link
Member

Hm, as far as I can tell, the BFS here finds nodes at all distances, rather than stopping once the layer with shortest distance is reached. This feels like a bug and probably means that its worst-case performance is worse than O(E sqrt V)?

(Very nice to improve the Hopcroft-Karp! It's a remnant of the olden days and not at all well optimized.)

@ahsoltan
Copy link
Contributor Author

ahsoltan commented Jan 24, 2026

I don't think this impacts complexity, as the O(E*sqrt(V)) complexity comes from the fact that there will be at most sqrt(V) iterations of the outer loop (source).
I'll test the early-break optimization on LC once it comes back up, but I don't expect it to be significant.

@ahsoltan
Copy link
Contributor Author

From a few tests (one, two) it seems that not breaking is significantly faster. Looks like computing all the distances allows a single dfs phase to push more than just the shortest paths. So I guess it should be fine to leave it that way?

@simonlindholm
Copy link
Member

Hm, yes, upon further reflection and testing it does seem like this is actually correct. One thing I find subtle is the fact that distances are only tracked on the LHS, so the DFS might find a path where the very last node found has another shorter path to it. This invalidates the property that levels don't decrease in the next phase. However, the property is maintained for the levels that are less than the shortest distance to an unmatched RHS node, and this is all we need in order to argue that the shortest distance to increase by one in each phase. Stress testing bears this out.

And yeah, it makes total sense that not breaking helps performance in practice. Will merge, thanks for the PR!

@simonlindholm simonlindholm merged commit 662c8a9 into kth-competitive-programming:main Jan 25, 2026
1 check passed
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.

2 participants