# I have n boys and n girls. I need to pair as much of them as possible for a dance in O(nlogn). Reduce this to a standard problem?

There are n girls and n boys. Each girl i has an objective attractiveness constant Pi (a natural number). The bigger the number, the more attractive. Each boy has a range in which he is comfortable asking the girl out [Ai, Bi] (inclusive). A boy will not ask someone out who is below Ai or above Bi.

I need to pair as many of them as I can for a single dance in O(n*logn) time.

I tried building some kind of a tree in O(n) and then using that three in O(logn) repeatedly against the whole list. I've spent some solid 3 hours on this problem and I'm really not getting anywhere. I've tried to build a dependency tree, I've treed weighted priority queues. I considered some constraint satisfaction algorithms, but as far as I recall they are all nowhere near O(n*logn).

Nothing seems to work. But I do clearly see that this has to be reduced to some other standard computer science problem.

However I've had no luck looking up "load balancing" or "pair assignment". I've no idea what are the right keywords.

This seems the be the kind of problem data centers have when assigning load to virtual machines. Or web requests over the world for large web sites. For example a server can sustain a load in [Ai, Bi] range (let's say RAM in GB's 4-8GB) and our target application needs 5GB. Now let's say we have n of both of these (target applications and servers). How to pair them so as much get paired? Thanks.

• Did you try sorting plus greedy assignment? Most attractive girl matched with a boy who would invite her, with the highest lower bound etc. – gnasher729 Nov 6 '17 at 8:10
• Thanks for the reply. :) So take the most attractive girl. Assign her to the boy who will take her, but has the least wiggle room. Then take next most attractive girl and again assign to the boy who will take her, but has the least wiggle room? And so on? Are you sure this will guarantee there is no other assignment with more pairs on the dance floor? – Edza Nov 6 '17 at 8:17
• In mathematics, when we are not sure of a claim we try to prove or disprove it. – Yuval Filmus Nov 6 '17 at 9:21
• The "standard" problem is called "marriage problem". – Raphael Nov 6 '17 at 9:28

Algorithm: Pick girl #i where $P_i$ is as high as possible. Eligible boys are those with $A_j ≥ P_i ≥ B_j$. If there is no eligible boy then she is not matched, otherwise match her with eligible boy #j, where $B_j$ is as large as possible. Then match the remaining boys and girls in an optimal way.