Here is one suggestion. I am not sure if this succeeds for any possible case, or if it is the most efficient possible algorithm.
Let n be the total number of indices. Create a priority priority queue of object type numbers, where each type of object is its index i . In other words, create a priority queue in which the sort values ββin the queue are F values. Associate each node with a list of all objects of this type. It takes O(n log(n)) .
For each type of object, starting from the type that has the most duplicates and moves to the type with the least number, connect one object from this "class" of objects with one object for each of the other classes that still have objects in them and delete this object from this node in the queue. Since each element of the queue, except the top one, will have fewer objects in it, most of the queue will still be in the order of priority; the top node, however, will have n-1 fewer elements (or it will be empty), so heapify down to maintain the queue. Also, delete nodes without objects. Repeat this process with the new highest queue value until all nodes are paired. It takes O(n log(n) + k) , where k is the total number of elements. Assuming k significantly greater than n , the total time complexity is O(k) .
Again, I am not entirely sure that this will always find a solution, if possible. My intuition is that if you re-type (if necessary) after each pairing, you will see that if a full connection is possible, it will , but (1) it will be much less effective, and (2) I'm not sure what cases this will happen if the original algorithm does not exist, and (3) I am not entirely sure that this will work every time.
As for which values ββof F have no solution, it is obvious that if there is one class of objects that has more elements than all other classes, it cannot be conjugated. Other than that ... I'm not sure. It would be interesting to investigate whether my βimprovedβ algorithm evaluates each case correctly or not.
source share