Edit: This answer assumes that the values โโfor inviting people are non-negative.
This problem can be solved using the greedy algorithm. Let's first discuss the case where the values โโare equal, so we are just trying to invite the maximum number of people. The main observation is that in any optimal solution you should always choose the person with the greatest number of direct or indirect bosses. Here is a brief explanation: why person X has the majority of bosses, and you have a choice that does not include person X Consider person Y among your choices, which is shared by most superiors with X Then you can do it better by choosing X instead of Y
So, at the first stage, we can always eagerly choose a person with senior management. Then the problem boils down to the same problem on several smaller trees. For example, suppose we select 3 invitees from the following tree:
A BC DEFG HIJKLMNO
Our first choice will be H , which automatically gives us D , B and A Then it remains to choose 2 of the three trees
IEC JKFG LMNO
The next best choice is L , etc.
We can do this efficiently because we just need to track the deepest child (not necessarily a straight child) of each node, which we can calculate in advance. Then we need some sort of priority queue data structure to select the best tree to select. If you selected k people from a hierarchy of size n , this should give the O(n + k log n) algorithm.
In order to extend this to the case when the values โโmay be unequal, basically the same idea works, except for the depth, you need to calculate the total cost of all the bosses. For each node X you track the child of Y , which has the most common value along the path between Y and X
source share