J: Draft Time

https://open.kattis.com/problems/drafttime

The algorithm used is a variant of the Gale-Shapley algorithm for stable matching:

While there exists an unmatched player pp who has not proposed to all teams:

  • Let tt be the most preferred team that pp has not proposed to

  • Assign pp to team tt

  • If tt was already full (i.e. already had MM players assigned), unassign the player that tt least prefers

Why does this algorithm work?

  1. This algorithm always gives MM players to each team. This is because players can't be unassigned from a team until the team has MM other players. So, a player will only be unassigned at the end if all teams are full, and since we have a surplus of players (i.e. NMKN \cdot M \leq K), all teams will be full.

  2. There are no instabilities after running the algorithm. Suppose toward contradiction that there were, then there existsPP who is undrafted or would prefer to go to team TT over the team he got drafted by, and TT can draft more players or prefers PP to an already drafted player. However, PP must have proposed to TT (since he is either undrafted or prefers TT to current choice), and TT must have unassigned PP because TT found MM more-preferred players. So, TT must not prefer PP to its already drafted players.

Note that this algorithm always completes, so there's no case where you should print Hello darkness my old friend!

For implementation, you can use priority queues per team (sorted by the team's player preferences) to store matches, a stack/queue to store unmatched players, a hash map to keep track of the number of teams proposed to by each player, and hash maps to keep track of team/player preferences.

While the stack/queue is not empty, remove a player and match them to their next team (if they haven't proposed to all teams) by inserting in the team's priority queue. Then, if the priority queue has M+1M+1 elements, pop the top (least preferred) player and add them back to the stack/queue.

Last updated